2011-11-07 19 views
0

查找表中的重复行我试过这个查询来获取重复记录。但是我得到这个错误。如何使用sql

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
select count(line_num), 
     line_num 
from codes 
where id = 35712 
     and isactive = 1 
group by line_num 
having count(line_num) > 1 
1
select code_id, line_num, count(*) from Codes 
where id = 35712 and isactive = 1 
group by code_id, line_num 
having count(*) > 1 
+0

如果我用主键组合,我没有得到任何记录。 – user957178

+0

如果code_id是主键,那么pair:code_id,line_num并不总是唯一的? –

+1

如果id是您的主键,则不能有多于一行的id为35712. – nos

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(第二列)具有重复值的所有code_ids,QT - 量。