【问题标题】:Postgres: aggregate column into arrayPostgres:将列聚合到数组中
【发布时间】:2016-08-08 19:11:01
【问题描述】:

我有以下两张表:

# select * from list;
  list_id |         name
 ---------+----------------------
        9 | Popular
       11 | Recommended

# 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 onlast_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

有什么可以简化的建议吗?

【问题讨论】:

  • 是否需要使用窗口函数?
  • 如果您的问题在order by,那么您可以在聚合中为某些聚合函数指定它,所以:select list_id, name, array_agg(game_id order by position) from list join list_item using (list_id) group by list_id, name; 应该足够了。
  • @AlexanderGuz 不,使用窗口不是必需的。抱歉,应该更清楚地说明这一点。
  • @Abelisto 谢谢,这确实简单多了。
  • 将其发布为答案,并最终接受它,因此问题不会得到解答。

标签: postgresql


【解决方案1】:

这是 Abelisto 在 cmets 中建议的更好的解决方案:

select
  list_id,
  name,
  array_agg(game_id order by position)
from list
join list_item
using (list_id)
group by list_id, name

【讨论】:

    猜你喜欢
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 2011-04-11
    • 2016-09-02
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多