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

时间:2011-11-07 19:44:45

标签: 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 aggregate function or the GROUP BY clause.

此处code_id是此表的主键。

任何人都可以帮我解决如何在此表中获取具有重复项的code_id。

由于

4 个答案:

答案 0 :(得分:4)

select count(line_num), 
       line_num 
from   codes 
where  id = 35712 
       and isactive = 1 
group  by line_num 
having count(line_num) > 1 

答案 1 :(得分:2)

它在line_num列中搜索重复值,其中code_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

第一列返回所有在line_num(第二列),qt - quantity中具有重复值的code_ids。

答案 2 :(得分:1)

select code_id, line_num, count(*) from Codes 
where id = 35712 and isactive = 1 
group by code_id, line_num
having count(*) > 1

答案 3 :(得分:1)

在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

参考文献: