我有一张桌子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 -----
答案 0 :(得分:3)
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
答案 1 :(得分:0)
使用聚合函数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
答案 2 :(得分:0)
您可以使用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)
这对您的测试数据对我有用。我得到所有拥有至少2个公司的Jns,然后将其与拥有C1公司的Jns相交
SELECT Jn
FROM T1
GROUP BY Jn
HAVING COUNT(Company) >= 2
INTERSECT
SELECT Jn
FROM T1
WHERE Company = 'c1'
GROUP BY Jn;