0

How can I transform query results into a aggregated rows? Probably not the best explanation, but this is the objective: (using SQL specifically)

Transform this:

Col1   Col2   
--------------
123    A
123    B
123    C
45     H 
45     K
45     L
89     A

Into this

Col1    Col2
--------------
123     A,B,C
45      H,K,L
89      A

Thanks in advance.

EDIT: Turns out this is a MSSQL Server version 2012

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
Maxcot
  • 1,513
  • 3
  • 23
  • 51
  • 1
    Good explanation. This feature varies by product. Which RDBMS are you using ([sql server](https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver15), [mysql](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat), [postgres](https://www.postgresql.org/docs/9.0/functions-aggregate.html), [oracle](https://docs.oracle.com/cd/E11882_01/server.112/e41084/functions089.htm#SQLRF30030), [snowflake](https://docs.snowflake.com/en/sql-reference/functions/listagg.html), etc)? – JNevill Sep 23 '21 at 20:05
  • Mostly MS SQL Server ... but a little SQLite – Maxcot Sep 23 '21 at 20:06
  • Depending on the version of sql server you can hit up that link in my comment above for `sql server`. If you are on an older version (older than sql server 2017), this gets a little trickier, but doable. For sqlite you can check out the `group_concat()` function: https://www.sqlitetutorial.net/sqlite-group_concat/ – JNevill Sep 23 '21 at 20:09
  • Well, I hadn't found anything, partially because I don't quite know how to describe the problem. But @JNevill for some reason understood immediatly. Thanks. – Maxcot Sep 23 '21 at 20:30
  • 1
    It can be tricky to ask this one. It has a lot of answers for every platform on stackoverflow because, as you encountered, if you don't know what to call it, it's hard to find information about it. Generally this is called "String Aggregation" and generally the function is `string_agg()`, `group_concat()`, or `listagg()` depending on the RDBMS and version of the RDBMS. Hopefully the links helped out :) – JNevill Sep 23 '21 at 21:21

0 Answers0