2011-11-07 16 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 - 量。