我有以下两个表:
# select * from list;
list_id | name
---------+----------------------
9 | Popular
11 | Recommended
and
# select * from list_item;
list_id | game_id | position
---------+---------+----------
11 | 2 | 0
9 | 10 | 1
11 | 5 | 1
11 | 4 | 4
11 | 6 | 2
11 | 7 | 3
9 | 3 | 0
我想要每个列表都有一组游戏 ID,如下所示:
list_id | name | game_ids
---------+-------------+------------
9 | Popular | {3,10}
11 | Recommended | {2,5,6,7,4}
我想出了以下解决方案,但它似乎相当复杂,尤其是我使用以下方法获得完整数组的部分distinct on
and last_value
:
with w as (
select
list_id,
name,
array_agg(game_id) over (partition by list_id order by position)
from list
join list_item
using (list_id)
)
select
distinct on (list_id)
list_id,
name,
last_value(array_agg) over (partition by list_id)
from w
有什么建议如何简化这个吗?
这是 Abelisto 在评论中建议的更好的解决方案:
select
list_id,
name,
array_agg(game_id order by position)
from list
join list_item
using (list_id)
group by list_id, name
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)