按结果获取组的所有模式的数组聚合

时间:2017-06-01 17:04:23

标签: postgresql

我有一堆~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~对于每个所有者的名字,我喜欢他们拥有最频繁宠物的阵列(如果他们有相同数量的相同宠物类型,则为宠物)。

一个例子:

*owner, pet type*
alice, cat
alice, dog
bob, fish
bob, cat
bob, fish
eve, cat
eve, dog
eve, cat
eve, dog

预期产出:

alice, [cat, dog]
bob, [fish]
eve, [cat, dog]

我的感觉是,这是“不同的”组合。在外部查询中使用array_agg进行内部查询以进行数组聚合 - 但我无法做到正确。

2 个答案:

答案 0 :(得分:1)

with data as (
select 'alice' as owner, 'cat' pet_type
union all select 'alice' as owner, 'dog'  pet_type
union all select 'bob' as owner, 'fish' pet_type
union all select 'bob' as owner, 'cat' pet_type
union all select 'bob' as owner, 'fish' pet_type
union all select 'eve' as owner, 'cat' pet_type
union all select 'eve' as owner, 'dog' pet_type
union all select 'eve' as owner, 'cat' pet_type
union all select 'eve' as owner, 'dog' pet_type
) , getMaxPet as (select owner , pet_type
from data d1
group by owner,pet_type
having count(pet_type) = (select max(pet_count) from (select count(pet_type) as pet_count
                from data d2
                where 
                d1.owner = d2.owner
                group by owner,pet_type  ) a ) )
select owner , array_agg(pet_type)
from getMaxPet
group by owner

试试这个,主要逻辑是根据每个用户找到所有宠物数量,然后选择拥有最大数量的宠物。

答案 1 :(得分:1)

您可以通过组合窗口功能和分组来完成此操作:

select owner, array_agg(pet order by pet)
from (
  select owner, pet, dense_rank() over (partition by owner order by count(*) desc) as rnk
  from pet
  group by owner, pet
) t
where rnk = 1
group by owner
order by owner;

在线示例:http://rextester.com/MTFIQ24341