如果组中至少有一个值符合条件,如何创建组?
以下是数据库表test
:
| ID | TYPE | COLOR |
|====|======|=======|
| 1 | 1 | R |
| 2 | 1 | B |
| 3 | 1 | G |
| 4 | 2 | B |
| 5 | 2 | G |
| 6 | 3 | G |
我需要选择具有多个行的所有TYPE
值,并且该TYPE中至少有一个COLOR为G.
所以伪选择看起来像这样:
select TYPE
from test
group by TYPE
having count(*) > 1
and count(COLOR = 'G') > 0
答案 0 :(得分:2)
根据OP的修改要求:
select type
from test
group by type
having count(*) > 1 and count(case when color = 'G' then 0 end) > 0
;
答案 1 :(得分:1)
count
仅计算非null
值。将两个必需条件都包含在一个中的巧妙技巧是计算返回G
的内容的case表达式的不同数量以及其他任何值的其他值:
SELECT type
FROM test
GROUP BY type
HAVING COUNT(DISTINCT CASE color WHEN 'G' THEN 1 ELSE 2 END) = 2
答案 2 :(得分:1)
您可以在计数(颜色)上使用内连接
select t1.type
from test t1
inner join (
select type, count(color)
from test
where type in (select type from test where color='G' )
group by type
) t2 on t1.type = t2.type
group by t1.type
having count(*) > 1
或以最简单的方式
select t1.type
from test t1
inner join test t2 on t1.type = t2.type and t2.color = 'G'
group by t1.type
having count(*) > 1