id | user_id | from_id | value | rating | order_id
1 | 1 | 2 | Ком | 5 | 1
2 | 2 | 1 | Ком2 | 2 | 1
3 | 3 | 4 | Ком3 | 5 | 2
4 | 4 | 3 | Ком4 | 2 | 2
[
{
order_id: 1,
comment1: {
name: 'Никита',
value: 'Ком',
rating: 5,
},
comment2: {
name: 'Владимир',
value: 'Ком2',
rating: 2,
},
}
]
WITH
cte1 AS (
SELECT jsonb_build_object('name', users.name,
'value', comments.value,
'rating', comments.rating) single_user,
comments.order_id,
'comment' || ROW_NUMBER() OVER (PARTITION BY comments.order_id ORDER BY comments.id) num
FROM users
JOIN comments ON users.id = comments.user_id
),
cte2 AS (
SELECT jsonb_build_object('order_id', order_id) ||
jsonb_object_agg(num, single_user) single_order
FROM cte1
GROUP BY order_id
)
SELECT jsonb_agg(single_order) final_data
FROM cte2;