SQL查找没有带值的列的重复行

时间:2013-12-20 13:37:55

标签: sql

我有一张类似于

的表格
transactionid | ordernumber
aaaa            1
aaaa            NULL
bbbb            2
bbbb            NULL
cccc            NULL

我需要在数据库中找到事务ID没有与之关联的订单号的行。因此,对于此示例,查询应仅返回cccc而不是aaaa或bbbb,因为存在与这些事务关联的订单号。

我尝试过很多东西,但没有运气。我敢肯定这很简单,我只是让它变得过于复杂。显然,如果我进行查询,其中ordernumber为NULL,我仍然会收到可能具有与之关联的ordernumbers的事务。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:6)

transactionid分组,并总结不是ordernumber的所有null。该金额必须为0

select transactionid 
from your_table
group by transactionid 
having sum(case when ordernumber is not null then 1 else 0 end) = 0