我有下面提到的表格:
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
答案 0 :(得分:1)
您可以使用自联接到同一张表,内部查询将计算每个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);
OR
select a.*
from table1 a
where (
select count(*)
from table1
where ID = a.ID
having sum(`Value` = 'DDD') > 0
) < 3
但是我更喜欢加入方式
答案 1 :(得分:1)
怎么样?
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')
输入和输出至少与您的情况相符。