获取与唯一id关联的特定值的计数

a2mppw5e  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(422)

我在下表提到:

ID       Value
U-1      ACB
U-1      ART
U-1      DDD
U-2      ACB
U-2      DDD
U-3      XCC
U-3      DFC

我想把那些行拿到哪里去 ValueDDD 但总计数是唯一的 ID 小于3。
所需输出:

ID       Value
U-2      ACB
U-2      DDD
wlwcrazw

wlwcrazw1#

这个怎么样?

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

epfja78i

epfja78i2#

您可以使用同一个表的自联接,内部查询将计算每个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

但我更喜欢加入法
更新的演示

相关问题