按两列分组,其中一列不为null

时间:2019-09-25 18:07:54

标签: sql oracle plsql group-by

我有下表:

c1   c2
1    5
1    6
2    5
2    null
3    null
3    null

expected: 1

这是NxM表,其中N是c1的不同值的数量,M是c2的不同值的数量,因此,对于不同的c1,总是存在相同数量的对(c1,c2)。

我想从с1列中选择一个值,为此c2中没有一个对应的空值。

我试图做GROUP BY(c1,null)HAVING(COUNT(*)= 0),但是没有用。

我该怎么办?

5 个答案:

答案 0 :(得分:1)

您可以按要区分的列进行分组,并仅对NULL中没有c2值的那些分组进行分组。 case用于总结这些条件

select c1
from your_table
group by c1
having sum(case when c2 is null then 1 else 0 end) = 0

答案 1 :(得分:0)

不存在

select c1 from table_name t1
where not exists ( select 1 from table_name t2 where t1.c1=t2.c1 
                               and t2.c2 is null)

答案 2 :(得分:0)

除了已经给出的答案外,您还可以使用NOT IN运算符来获得结果,如下所示:

Select distinct c1 from your_table
Where c1 not in 
(select t.c1 from your_table t
Where t.c2 is null 
and t.c1 is not null);

干杯!

答案 3 :(得分:0)

这是另一种方法

select c1
from your_table
group by c1
having count(c1)=count(c2);

答案 4 :(得分:-1)

从表1中选择c1 c2不为空;