代码之家  ›  专栏  ›  技术社区  ›  user8834780

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

  •  1
  • user8834780  · 技术社区  · 6 年前

    假设我有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 回复  |  直到 6 年前
        1
  •  1
  •   Gordon Linoff    6 年前

    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;
    

    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;