代码之家  ›  专栏  ›  技术社区  ›  Mohammad Yusuf

Group By和Filter on 2 distinct values on other column,其中1个值是必需的

  •  0
  • Mohammad Yusuf  · 技术社区  · 7 年前

    我有张T1桌

    Jn company
    X1 c1
    X1 c2
    X1 c3
    Y2 c1
    Y2 c2
    Y2 c3
    Z3 c2
    Z3 c3
    Z3 c4
    

    我想按JN分组,只筛选那些至少有2家反垄断公司的记录,其中1家应该是C1。

    期望结果:

    X1
    Y2
    

    我是这样想的

    select Jn from T1
    group by Jn
    having -----
    
    4 回复  |  直到 7 年前
        1
  •  3
  •   juergen d    7 年前
    select Jn
    from your_table
    group by Jn
    having count(distinct company) >= 2 
       and sum(case when company = 'c1' then 1 else 0 end) > 0
    
        2
  •  0
  •   Yogesh Sharma    7 年前

    你可以使用 exists :

    select t1.Jn 
    from table t1
    where exists (select 1 from table t2 where t2.jn = t1.jn and t2.company = 'c1')
    

    编辑:

    select t1.Jn 
    from table t1
    group by jn
    having count(distinct company) >= 2 and
           sum(case when company = 'c1' then 1 else 0 end) > 0;
    
        3
  •  0
  •   Zaynul Abadin Tuhin    7 年前

    使用聚合函数 count()

        select Jn  from T1          
        group by jn
        having count(distinct company)>=2
        and sum(case when company='c1' then 1 else 0 end)>0
    
        4
  •  0
  •   user1443098    7 年前

    这对你的测试数据很有用。我得到所有至少有两个公司的JN,然后与那些有C1公司的JN相交。

    SELECT Jn
    FROM T1
    GROUP BY Jn
    HAVING COUNT(Company) >= 2
    
    INTERSECT
    
    SELECT Jn
    FROM T1
    WHERE Company = 'c1'
    GROUP BY Jn;