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
参考资料: