通过具有与唯一 ID 关联的特定值来获取计数
Get count with having particular value associated with unique id
我在下面提到了 table:
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
您可以使用自连接 table,内部查询将计算每个 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
但我更喜欢加入方法
这个怎么样?
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')
输入和输出至少在我这边与你的情况相匹配。
我在下面提到了 table:
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
您可以使用自连接 table,内部查询将计算每个 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
但我更喜欢加入方法
这个怎么样?
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')
输入和输出至少在我这边与你的情况相匹配。