SQL使用满足条件的列计数行

时间:2015-11-05 05:08:46

标签: mysql sql

假设我有一个包含列ID和内容填充数据的表。

ID | Content
1  | a
1  | b
1  | c
2  | b
2  | a
3  | b

我想找到每个至少包含其中一个''''和' c'所以返回的表将是:

ID | Content
1  | a
1  | b
1  | c

3 个答案:

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