DB2 sql group by / count distinct列值

时间:2020-12-30 22:44:47

if I have a table with values like this:

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

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

and I would like to get all the ID's where 'FLAG' is only set to 1, so in this case the query would return

我想得到所有的ID''FLAG'只设置为1,所以在这种情况下查询将返回

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

How can I achieve this?

我怎样才能做到这一点?

2 个解决方案

#1


2  

try this:

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

#2


1  

I don't have a db2 instance to test on but this might work:

我没有要测试的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;

#1


2  

try this:

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

#2


1  

I don't have a db2 instance to test on but this might work:

我没有要测试的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;