Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL create an array from several rows

I have a table with a one to many mapping from ID to some_value. What query can give me all of some_value for a particular ID?

I can use any array, string, or other object useful in SQL as the final result in list_of_values. You don't need to use my comma seperated format.

My particular varient of SQL is Hive, but the syntax and functions are very similar to MySQL :)

Starting table:

ID             some_value
-----------    ------------
1              a
1              b
1              c
2              x
2              y
2              z
2              a
3              g
3              h

Finished table:

ID              list_of_values
----------      ----------------
1               a, b, c
2               x, y, z, a
3               g, h
like image 934
Don P Avatar asked Sep 20 '26 20:09

Don P


1 Answers

SELECT ID, COLLECT_SET(some_value) AS list_of_values
    FROM YourTable 
    GROUP BY ID;
like image 125
Joe Stefanelli Avatar answered Sep 23 '26 13:09

Joe Stefanelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!