Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.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 如何使用sql查找表中的重复行_Sql Server_Sql Server 2005_Sql Server 2008 - Fatal编程技术网

Sql server 如何使用sql查找表中的重复行

Sql server 如何使用sql查找表中的重复行,sql-server,sql-server-2005,sql-server-2008,Sql Server,Sql Server 2005,Sql Server 2008,我已尝试此查询以获取重复记录。但我遇到此错误 select * from Codes where id = 35712 and isactive = 1 group by line_num having count(*) > 1 Msg 8120, Level 16, State 1, Line 1 Column 'Codes.code_id' is invalid in the select list because it is not contained in either an a

我已尝试此查询以获取重复记录。但我遇到此错误

select * from Codes
where id = 35712 and isactive = 1
group by line_num
having count(*) > 1
Msg 8120, Level 16, State 1, Line 1
Column 'Codes.code_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
我得到了这个错误

select * from Codes
where id = 35712 and isactive = 1
group by line_num
having count(*) > 1
Msg 8120, Level 16, State 1, Line 1
Column 'Codes.code_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
这里,code_id是该表的主键

有谁能帮我找到这个表中有重复项的代码id吗


感谢

它在第_num行列中搜索重复的值,其中代码_id是代码表的主键。我不知道确切的表定义,所以这有点猜测

select c.code_id, c.line_num, t.qt from codes c
join (
    select line_num, count(*) as qt
    from codes
    where id = 35712 and isActive = 1
    group by line_num
    having count(*) > 1
) as t on t.line_num = c.line_num

第一列返回所有代码ID,这些代码ID在第_num行(第二列)qt-quantity中有重复的值。

在SQL Server 2005及更高版本中,您可以使用聚合窗口函数:

;WITH counted AS (
  SELECT
    *,
    Cnt = COUNT(*) OVER (PARTITION BY line_num)
  FROM Codes
  WHERE id = 35712
    AND isactive = 1
)
SELECT *
FROM counted
WHERE Cnt > 1
参考资料:


如果我使用主键进行分组,我不会得到任何记录。如果code\u id是主键,那么pair:code\u id,line\u num并不总是唯一的?如果id是主键,则不能有多个id为35712的行。在这里,id可以是多个记录,但ba\u code\u id应该是主键。您如何向我们展示您的表定义?就像现在一样,你只是随机地给我们提供关于专栏的额外信息。。。