1

Duplicate of question How to use GROUP BY to concatenate strings in SQL Server?

I have a table where I want to perform a similar groupby as illustrated with pandas. So for each group find the unique values of the relevant column and (assuming it is a string) concatenate them into one string seperated by comma. How can such a query be performed in SQL?

>>> import pandas as pd
>>> raw_table = pd.DataFrame(data = {'key1':[1,2,1,2,1,3,1],'key2':['a','b','c','a','b','c','a']})
>>> raw_table.groupby('key1').key2.apply(lambda x:",".join(set(x)))
key1
1    a,c,b
2      a,b
3        c
Name: key2, dtype: object
Peter Mølgaard Pallesen
  • 1,470
  • 1
  • 15
  • 26
  • 3
    Please rewrite your data in the form of tables, and also tell us which _version_ of SQL you are using (e.g. MySQL, SQL Server, etc.). "SQL" is just a language, not an actual product. – Tim Biegeleisen Apr 03 '19 at 07:40
  • 1
    I have no idea what that code is supposed to do - and I would guess that not everyone who is proficient in "SQL" understands the code that you have written (whatever language that is). To illustrate your problem, please **[edit]** your question (by clicking on the [edit] link below it) and add some [sample data](https://meta.stackexchange.com/questions/81852) and the expected output based on that data –  Apr 03 '19 at 07:43
  • This answer is about how to solve your problem in SQL server: https://stackoverflow.com/questions/44918658/sql-server-join-rows-into-comma-separated-list There is no standard way of solving your problem that would apply to any SQL dialect, so you need to specify which SQL variant you are using – mortb Apr 03 '19 at 07:48
  • Make it easy (possible) to assist you: https://stackoverflow.com/help/mcve – jarlh Apr 03 '19 at 07:53
  • Thanks for your comments. Can anyone with higher reputation than me, close the question and mark it is duplicate? – Peter Mølgaard Pallesen Apr 03 '19 at 10:48

0 Answers0