Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to get aggregated result in comma separators along with group by column in SQL Server

I need to write a sql query on the table such that the result would have the group by column along with the aggregated column with comma separators.

My table would be in the below format

   |`````````|````````|
   |    ID   |  Value |
   |_________|________|
   |    1    |   a    |
   |_________|________|
   |    1    |   b    |
   |_________|________|
   |    2    |   c    |
   |_________|________|

Expected result should be in the below format

   |`````````|````````|
   |    ID   |  Value |
   |_________|________|
   |    1    |  a,b   |
   |_________|________|
   |    2    |   c    |
   |_________|________|
like image 983
suryakiran Avatar asked Jun 14 '11 14:06

suryakiran


People also ask

How do you get comma separated column values in SQL query?

In order to fetch the comma separated (delimited) values from the Stored Procedure, you need to make use of a variable with data type and size same as the Output parameter and pass it as Output parameter using OUTPUT keyword.

Can I use GROUP BY with aggregate function?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

Can we use GROUP BY and count together in SQL?

We can use GROUP BY to group together rows that have the same value in the Animal column, while using COUNT() to find out how many ID's we have in each group. It returns a table with three rows (one for each distinct animal).


1 Answers

You want to use FOR XML PATH construct:

select 
    ID, 
    stuff((select ', ' + Value 
           from YourTable t2 where t1.ID = t2.ID 
           for xml path('')),
          1,2,'') [Values]
from YourTable t1
group by ID

The STUFF function is to get rid of the leading ', '.

You can also see another examples here:

  • SQL same unit between two tables needs order numbers in 1 cell
  • SQL and Coldfusion left join tables getting duplicate results as a list in one column
like image 192
Adriano Carneiro Avatar answered Sep 26 '22 06:09

Adriano Carneiro