获取具有与唯一ID相关联的特定值的计数

时间:2018-06-20 12:07:10

标签: mysql uniqueidentifier

我有下面提到的表格:

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

2 个答案:

答案 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);

Demo

OR

select a.*
from table1 a
where  (
    select count(*)
    from table1
    where ID = a.ID 
    having sum(`Value` = 'DDD') > 0
) < 3

但是我更喜欢加入方式

updated demo

答案 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')

输入和输出至少与您的情况相符。

演示:http://rextester.com/AZLA7822