sql – 作为聚合函数的数组联合
发布时间:2020-12-12 06:41:02 所属栏目:MsSql教程 来源:网络整理
导读:我有以下输入: name | count | options-----------------------user1 | 3 | ['option1','option2']user1 | 12 | ['option2','option3']user2 | 2 | ['option1','option3']user2 | 1 | [] 我想要以下输出: name | count | options-----------------------use
我有以下输入:
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 http://rextester.com/YTZ45626 我知道这可以通过定义自定义聚合函数轻松完成,但我想通过查询来完成.我理解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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |