简体   繁体   中英

showing non aggregate column in a group by query in SQL

i have a table in SQL 2008 as

ID     Items
1      A
1      B
2      C
3      D
3      B

i would like to get the result as

ID    Items
1     A,B
2     C
3     B,D

I have used cursors but it has considerably slowed the process , can i achieve the above result using group by query or through any other way.

Thanks and Regards

Kapil

You are looking for a way to concatenate the results. I don't think MSSQL has a function for that, but here's a very nice tutorial on how to create a method like that: http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/

I think

GROUP_CONCAT

is the function you are looking for. Something like

SELECT id,
       GROUP_CONCAT (DISTINCT Items ORDER BY Items SEPARATOR ',')
    FROM my_table
    GROUP BY id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM