1

Hi i have a table like this;

+----+----------+-------------+
| id | room_id  |    house_id |
+----+----------+-------------+
|  1 |        1 |           1 |
|  2 |        2 |           1 |
|  3 |        3 |           1 |
|  4 |        1 |           2 |
|  5 |        2 |           2 |
|  6 |        3 |           2 |
|  7 |        1 |           3 |
|  8 |        2 |           3 |
|  9 |        3 |           3 |
+----+-------+----------------+

and i want to create a view like this

+----+----------+-------------+
| id | house_id |       rooms |
+----+----------+-------------+
|  1 |        1 |     [1,2,3] |
|  2 |        2 |     [1,2,3] |
|  3 |        3 |     [1,2,3] |
+----+-------+----------------+

i tried many ways but i cant gruop them in one line

Thanks for any help.

1 Answer 1

2

You can use array_agg():

select house_id, array_agg(room_id order by room_id) as rooms
from t
group by house_id;

If you want the first column to be incremental, you can use row_number():

select row_number() over (order by house_id) as id, . . . 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.