0

I want to write a query which will display the following result

FROM

  ID      Contract#          Market
   1       123kjs             40010
   1       123kjs             40011
   2       121kjs             40098
   2       121kjs             40099

TO

  ID      Contract#          Market
   1       123kjs             40010,40011
   2       121kjs             40098,40099
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
MSTR Prime
  • 41
  • 4

3 Answers3

0

Try out this query, I use GROUP_CONCAT to turn column fields into 1 row field.

Also notice that you should rename the FROM clause with the name of your table.

 SELECT ID,Contract#, GROUP_CONCAT(Market SEPARATOR ',') 
    FROM nameOfThatTable GROUP BY ID;
Nin-ya
  • 242
  • 1
  • 12
0

Try this out. I used PIVOT to solve it.

  SELECT 
         ID,
         Contract#,
         ISNULL(CONVERT(varchar,[40010]) + ',' + CONVERT(varchar,[40011]),
         CONVERT(varchar,[40098]) + ',' + CONVERT(varchar,[40099])) AS Market FROM
  ( SELECT * FROM ContractTable) AS A
  PIVOT(MIN(Market) FOR Market IN ([40010],[40011],[40098],[40099])) AS PVT
  ORDER BY ID
Rigel1121
  • 1,992
  • 1
  • 16
  • 24
0

You can use ', ' + CAST(Market AS VARCHAR(30)) in sub-query and join Id and Contract# of sub-query with outer query to get values of Market as Comma Separated Values for each Id and Contract#.

SELECT DISTINCT ID,Contract#,
SUBSTRING(
         (SELECT  ', ' + CAST(Market AS VARCHAR(30))
         FROM #TEMP T1
         WHERE T2.Id=T1.Id AND T2.Contract#=T1.Contract#             
         FOR XML PATH('')),2,200000) Market
FROM #TEMP T2

Note
.........

If you want to get CSV values for Id only, remove T2.Contract#=T1.Contract# from sub-query.

Community
  • 1
  • 1
Sarath KS
  • 18,103
  • 11
  • 73
  • 80
  • Did u get the output? Please reply @Bibek Shrestha – Sarath KS Feb 28 '15 at 17:04
  • 1
    I tend to use `STUFF(, 1, 2, '')` instead of `SUBSTRING()` as it avoids a bug when the expression gets larger than the arbitrarily chosen large number. But this is the idiomatic way. – Ben Thul Feb 28 '15 at 17:06