sql – 作为聚合函数的数组联合

前端之家收集整理的这篇文章主要介绍了sql – 作为聚合函数的数组联合前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下输入:
  1. name | count | options
  2. -----------------------
  3. user1 | 3 | ['option1','option2']
  4. user1 | 12 | ['option2','option3']
  5. user2 | 2 | ['option1','option3']
  6. user2 | 1 | []

我想要以下输出

  1. name | count | options
  2. -----------------------
  3. user1 | 12 | ['option1','option2','option3']

我按名字分组.对于每个组,计数应该作为最大值聚合,并且选项应该聚合为联合.我正在弄清楚如何解决后者.

目前,我有这个查询

  1. with data(name,count,options) as (
  2. select 'user1',12,array['option1','option2']::text[]
  3. union all
  4. select 'user1',array['option2','option3']::text[]
  5. union all
  6. select 'user2',2,1,array[]::text[]
  7. )
  8. select name,max(count)
  9. from data
  10. group by name

http://rextester.com/YTZ45626

我知道这可以通过定义自定义聚合函数轻松完成,但我想通过查询来完成.我理解unfst()数组的基础知识(以及稍后的结果的array_agg()),但无法弄清楚如何在我的查询中注入它.

解决方法

您可以使用FROM列表中的unnest(options)隐式横向连接,然后使用array_agg(distinct v)创建一个包含以下选项的数组:
  1. with data(name,array_agg(distinct v) -- the 'v' here refers to the 'f(v)' alias below
  2. from data,unnest(options) f(v)
  3. group by name;
  4. ┌───────┬───────────────────────────┐
  5. name array_agg
  6. ├───────┼───────────────────────────┤
  7. user1 {option1,option2,option3}
  8. user2 {option1,option3}
  9. └───────┴───────────────────────────┘
  10. (2 rows)

猜你在找的MsSQL相关文章