所有孩子都符合条件的Groupby

时间:2014-01-15 16:53:58

标签: sql oracle

我有一张桌子:

+--+---------+------+
|ID|Parent_ID|Status|
+--+---------+------+
|1 |0        |      |
+--+---------+------+
|2 |0        |      |
+--+---------+------+
|3 |1        |A     |
+--+---------+------+
|4 |1        |B     |
+--+---------+------+
|5 |1        |C     |
+--+---------+------+
|6 |2        |A     |
+--+---------+------+
|7 |2        |B     |
+--+---------+------+

我想得到父母的身份证,以及孩子的数量,但我们会选择所有孩子都有状态A或B的小组

基于上表我只想看到: 2,2

select parent_id,count(1) from MYTABLE
where parent_id != 0
group by parent_id
HAVING (status) IN
   ('A','B')

2 个答案:

答案 0 :(得分:2)

仅选择状态为零而不是AB

的状态
select parent_id, count(1) 
from MYTABLE
where parent_id != 0
group by parent_id
HAVING sum(case when status NOT IN ('A','B') then 1 else 0 end) = 0

答案 1 :(得分:2)

试试这个:

SELECT Parent_ID, COUNT(ID) 
FROM Table
WHERE Parent_ID <> 0 
      AND Parent_ID NOT IN
      (
         SELECT DISTINCT(Parent_ID) FROM Table WHERE Status NOT IN ('A', 'B')
      )
GROUP BY Parent_ID
相关问题