0

In a query like this one:

SELECT * 
FROM `Order`
WHERE `CustID` = '1'

My results are displayed like so:

| CustID| Order |
-----------------
| 1     | Order1|
| 1     | Order2|
| 1     | Order3|
-----------------

How do I write SQL statement, to get a result like this one?:

| CustID| Order                 |
---------------------------------
| 1     | Order1, Order2, Order3|
---------------------------------

In mySQL it's possible with Group_Concat, but in SQL Server it gives error like syntax error or some.

shA.t
  • 16,580
  • 5
  • 54
  • 111
Sam
  • 471
  • 2
  • 5
  • 9

3 Answers3

6

Use xml path (see fiddle)

SELECT distinct custid, STUFF((SELECT ',' +[order]
FROM table1 where custid = t.custid
FOR XML PATH('')), 1, 1, '')
FROM table1 t
where t.custid = 1

STUFF replaces the first , with an empty string, i.e. removes it. You need a distinct otherwise it'll have a match for all orders since the where is on custid.

FOR XML
PATH Mode
STUFF

artm
  • 8,554
  • 3
  • 26
  • 43
4

You can use Stuff function and For xml clause like this:

 SELECT DISTINCT CustId, STUFF((
   SELECT ','+ [Order]
   FROM [Order] T2
   WHERE T2.CustId = T1.CustId
   FOR XML PATH('')
 ), 1, 1, '')
 FROM  [Order] T1

fiddle here

Note: Using order as a table name or a column name is a very, very bad idea. There is a reason why they called reserved words reserved.
See this link for my favorite way to avoid such things.

Community
  • 1
  • 1
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
-1

try this. Change table name and column names for what you need;

SELECT custID, 
       LISTAGG(Order, ', ') WITHIN GROUP (ORDER BY Order) text
  FROM table_name
 GROUP BY custID

edit for MSSQL . You should use group_concat function.

SELECT custID, GROUP_CONCAT(Order)
  FROM table_name
 WHERE CustID = 1
 GROUP BY custID;
Onur Cete
  • 263
  • 1
  • 2
  • 10