Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 禁用基于两个group by列的重复数据,并使用check not null_Sql Server_Tsql_Sql Server 2016 - Fatal编程技术网

Sql server 禁用基于两个group by列的重复数据,并使用check not null

Sql server 禁用基于两个group by列的重复数据,并使用check not null,sql-server,tsql,sql-server-2016,Sql Server,Tsql,Sql Server 2016,我使用下面的查询返回两列重复的行,但它返回的行值为空。我希望返回两列都不为NULL的行。另外,如何停用旧ID的重复记录 With deactivaterows as ( Select t.*, count(*) over (partition by col1, col2) as cnt from TABLE1 t) Select * from deactivaterows where cnt > 1; 我会这样做: select col1, col2, count(*) fro

我使用下面的查询返回两列重复的行,但它返回的行值为空。我希望返回两列都不为NULL的行。另外,如何停用旧ID的重复记录

With deactivaterows as (

  Select t.*, count(*) over (partition by col1, col2) as cnt from TABLE1 t)

Select * from deactivaterows where cnt > 1;

我会这样做:

select col1, col2, count(*) 
from TABLE1 
where col1 is not null and col2 is not null
group by col1, col2 
having count(*) > 1
having命令很棒,它在groupby和select之后过滤结果。您可以随时输入where,而这将在开始分组、计数或选择任何内容之前进行比较

或者,您当然可以通过插入where子句来修改现有解决方案,而不会产生问题:

With deactivaterows as (

  Select t.*, count(*) over (partition by col1, col2) as cnt from TABLE1 t 
  where col1 is not null and col2 is not null)

Select * from deactivaterows where cnt > 1;

您希望行号不计算*:

with deactivaterows as
(
select t.*, row_number() over(partition by t.col1, t.col2 order by (select null)) as rn
from TABLE1
where t.col1 is not null and t.col2 is not null
)
select * from deactivaterows where rn > 1

如果使用此选项,请记住它将返回除一行以外的所有重复行,我建议在over语句中使用order by,以确保得到的是实际重复的行,而不是要保留的行。@TimLeaf问题语句需要澄清。我主要是指出应该使用row_number而不是count。这绝对是一个很好的观点,特别是如果他们想自动停用最新创建的行,例如,保留最旧的行不变。