Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert several duplicate rows into an array in SQL (Postgres)?

I have the following table One:

 id │ value 
────┼───────
  1 │ a
  2 │ b

And Two:

  id │ value 
─────┼───────
  10 │ a
  20 │ a
  30 │ b
  40 │ a
  50 │ b

One.value has a unique constraint but not Two.value (one-to-many relationship).

Which SQL (Postgres) query will retrieve as array the ids of Two whose value match One.value? The result I am looking for is:

          id │ value 
─────────────┼───────
  {10,20,40} │ a
     {30,50} │ b
like image 640
ehmicky Avatar asked Oct 23 '25 16:10

ehmicky


1 Answers

Check on SQL Fiddle

SELECT array_agg(id) AS id, "value"
  FROM Two
 GROUP BY "value";

Using value as identifier (column name here) is a bad practice, as it is a reserved keyword.

like image 78
vyegorov Avatar answered Oct 25 '25 06:10

vyegorov