我有以下输入:
- name | count | options
- -----------------------
- user1 | 3 | ['option1','option2']
- user1 | 12 | ['option2','option3']
- user2 | 2 | ['option1','option3']
- user2 | 1 | []
我想要以下输出:
- name | count | options
- -----------------------
- user1 | 12 | ['option1','option2','option3']
我按名字分组.对于每个组,计数应该作为最大值聚合,并且选项应该聚合为联合.我正在弄清楚如何解决后者.
目前,我有这个查询:
- with data(name,count,options) as (
- select 'user1',12,array['option1','option2']::text[]
- union all
- select 'user1',array['option2','option3']::text[]
- union all
- select 'user2',2,1,array[]::text[]
- )
- select name,max(count)
- from data
- group by name
我知道这可以通过定义自定义聚合函数轻松完成,但我想通过查询来完成.我理解unfst()数组的基础知识(以及稍后的结果的array_agg()),但无法弄清楚如何在我的查询中注入它.
解决方法
您可以使用FROM列表中的unnest(options)隐式横向连接,然后使用array_agg(distinct v)创建一个包含以下选项的数组:
- with data(name,array_agg(distinct v) -- the 'v' here refers to the 'f(v)' alias below
- from data,unnest(options) f(v)
- group by name;
- ┌───────┬───────────────────────────┐
- │ name │ array_agg │
- ├───────┼───────────────────────────┤
- │ user1 │ {option1,option2,option3} │
- │ user2 │ {option1,option3} │
- └───────┴───────────────────────────┘
- (2 rows)