DB2 sql group by / count distinct列值

时间:2012-10-24 11:42:00

标签: sql db2

如果我有一个像这样的值的表:

ID  SUBID    FLAG
-----------------
 1      1       1
 1      2  (null)
 2      3       1
 2      3  (null)
 3      4       1
 4      5       1
 4      6  (null)
 5      7       0
 6      8  (null)
 7      9       1

我希望得到所有ID,其中'FLAG'仅设置为1,因此在这种情况下查询将返回

ID  SUBID    FLAG
-----------------
 3      4       1
 7      9       1

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT * FROM flags where flag=1
and ID NOT in( SELECT ID FROM flags where flag !=1 OR flag IS NULL)

答案 1 :(得分:1)

我没有要测试的db2实例,但这可能有效:

select t1.id, t1.subid, t1.flag
from yourtable t1
inner join
(
  select id 
  from yourtable 
  group by id
  having count(id) = 1
) t2
  on t1.id = t2.id
where t1.flag = 1;