基于另一个分组的条件分组

时间:2018-07-27 20:58:59

标签: sql amazon-redshift

假设我有3个小组,4个顾问和3个客户:

group_id advisor_id client_id assets
1        1          1         100
1        2          2         200
2        3          
3        4          3         300

您能协助获得:

count groups with 1 advisor_id (=2)
count groups with > 1 advisor_id (=1)
count clients for groups with 1 advisor_id (=1)
count clients for groups with >1 advisor id (=2)

我尝试了以下变化: select case when count(advisor_id) over(partition by group_id)=1 then count(distinct group_id) end

select case when count(advisor_id)=1 then count(distinct client_id) end

但是这些没有给我我想要的东西。

1 个答案:

答案 0 :(得分:1)

您将使用多个聚合。例如,对于前两个,我将使用直方图查询::

select cnt, count(*), min(group_id), max(group_id)
from (select group_id, count(distinct adviser_id) as cnt
      from t
      group by group_id
     ) t
group by cnt;

您特别关心“ 1”或“大于1”。为此,我可以这样表述:

select sum(case when cnt = 1 then 1 else 0 end) as only_1,
       sum(case when cnt > 1 then 1 else 0 end) as more_than_1
from (select group_id, count(distinct adviser_id) as cnt
      from t
      group by group_id
     ) t;