假设我有一个包含列ID和内容填充数据的表。
ID | Content
1 | a
1 | b
1 | c
2 | b
2 | a
3 | b
我想找到每个至少包含其中一个''''和' c'所以返回的表将是:
ID | Content
1 | a
1 | b
1 | c
答案 0 :(得分:2)
使用条件SUM
验证group id
内是否存在每个元素的1个或多个。
然后选择DISTINCT ID, Content
以消除可能的重复
SELECT DISTINCT ID, Content
From YourTable
WHERE ID IN (SELECT ID
FROM YourTable
GROUP BY ID
HAVING SUM(case when Content = 'a' then 1 else 0 end) >= 1
AND SUM(case when Content = 'b' then 1 else 0 end) >= 1
AND SUM(case when Content = 'c' then 1 else 0 end) >= 1
)
答案 1 :(得分:0)
select * from (
where
Select ID ,SUM(case when Content = 'a' then 1 else 0 end) as sum_a ,UM(case when Content = 'b' then 1 else 0 end) as sum_b,
SUM(case when Content = 'c' then 1 else 0 end) as sum_c
FROM table
Group by ID)x
where x.sum_a >1 or sum_b>1 or sum_c>1
答案 2 :(得分:0)
这是另一种检查每个ID的特定数量的不同“内容”项目的方法。 Here是指向此解决方案的SQL Fiddle的链接。
select
id,
count(distinct(content))
from tableX
group by id
having count(distinct(content)) = 3;