SQL Server:使用NULL查找重复行

时间:2018-10-15 18:51:54

标签: sql-server tsql duplicates

我需要在SQL Server表中找到重复的行。问题在于值可能为NULL。我有以下代码,只要单元格不为NULL,似乎就可以正常工作:

select s.ID, t.* 
from [Data] s
join (select Term1, Term2, Term3, Term4, count(*) as cnt
      from [Data]
      group by Term1, Term2, Term3, Term4
      having count(*) > 1) t on s.Term1 = t.Term1 
                             and s.Term2 = t.Term2 
                             and s.Term3 = t.Term3 
                             and s.Term4 = t.Term4

如何修改它,即使有NULL值(如

)也能找到重复项
Term1    Term2    Term3    Term4
--------------------------------
hello    NULL     okay     NULL
hello    NULL     okay     NULL

2 个答案:

答案 0 :(得分:4)

您可以使用COUNT(*) OVER()

WITH cte AS (
  SELECT *, COUNT(*) OVER(PARTITION BY Term1, Term2, Term3, Term4) AS cnt
  FROM [Data]
)
SELECT *
FROM cte
WHERE cnt > 1

答案 1 :(得分:0)

确定要返回重复的两行吗?您的内部查询可用于识别重复的行,也可以将计数添加为其他列。返回每一行有什么好处?