以下是我提到的表格:
ID Value
U-1 ACB
U-1 ART
U-1 DDD
U-2 ACB
U-2 DDD
U-3 XCC
U-3 DFC我想获取那些行,其中Value是DDD,但是唯一ID的总数是<3。
所需产出:
ID Value
U-2 ACB
U-2 DDD发布于 2018-06-20 13:13:11
可以对同一个表使用自联接,内部查询将计算每个id的计数,并在计数小于3的情况下筛选行
select a.*
from table1 a
join (
select id, count(*) total
from table1
group by id
having total < 3
and sum(`Value` = 'DDD') > 0
) t using(id);演示
或
select a.*
from table1 a
where (
select count(*)
from table1
where ID = a.ID
having sum(`Value` = 'DDD') > 0
) < 3但我更喜欢加入法
更新演示
发布于 2018-06-20 13:28:30
这个怎么样?
SELECT * FROM
(SELECT * FROM sof t1
WHERE (SELECT COUNT(id) FROM sof t2 WHERE t2.id = t1.id) < 3) as temp2
WHERE id IN (SELECT id FROM sof WHERE value = 'DDD')至少在我的结尾,输入和输出与您的情况相匹配。
演示:http://rextester.com/AZLA7822
https://stackoverflow.com/questions/50947870
复制相似问题