使用主键获取重复记录

时间:2011-09-09 03:16:25

标签: sql

iam使用sqso我有3个字段:

ID        CustomerNo        Date
1           0009                9/9/2011
2           0009                9/9/2011
3           0009                9/9/2011
4           0010                9/9/2011

我想确定具有相同customerno和date的记录,并获取每个唯一ID。

ID        CustomerNo        Date
1           0009                9/9/2011
2           0009                9/9/2011
3           0009                9/9/2011

我该怎么做?我试过这段代码:

SELECT DISTINCT S1.ID,  S1.customerno, S1.DATE
FROM TABLE AS S1
INNER JOIN TABLE AS S2
ON  S1.DATE=S2.DATE AND S1.CUSTOMERNO=S2.CUSTOMERNO 
AND S2.id <= S1.id
GROUP BY S1.customerno, S1.id , S1.DATE

但它也获得了第4号记录,不同的客户没有,但具有相同的日期。

我想只获得那些在customerno和date中重复的内容。

3 个答案:

答案 0 :(得分:7)

如果我理解正确,则此查询会给出重复的客户编号和日期。 (我的表名为“t”;我不能使用“table”作为表名。)

select customerno, date
from t
group by customerno, date
having count(*) >= 2

要获取这些“重复”客户的ID号,请将其加入原始表。

select t.id, t.customerno, t.date
from t
inner join
    (select customerno, date
     from t
     group by customerno, date
     having count(*) >= 2) dups 
  on dups.customerno = t.customerno and dups.date = t.date

答案 1 :(得分:0)

SELECT 
    DISTINCT S1.ID,  S1.customerno, S1.DATE 
FROM TABLE AS S1 
INNER JOIN TABLE AS S2 ON S1.DATE = S2.DATE 
WHERE 
    S1.DATE = S2.DATE 
    AND S1.CUSTOMERNO = S2.CUSTOMERNO 
    AND S2.id <= S1.id 
GROUP BY 
    S1.customerno, S1.id , S1.DATE

试试此代码

答案 2 :(得分:0)

如果“CustomerNo”是您正在讨论的唯一ID,则此查询可能适合您。

Select Count(*) as #OfDuplicates, CustomerNo, Date
From Table
Group By CustomerNo, Date
Having Count(*)>1

如果您希望将最后一行的键作为样本引用,则可以使用此查询。这也避免了使用子查询。

Select Count(*) as #OfDuplicates, CustomerNo, Date, Max(Id) as SampleInstanceId
From Table
Group By CustomerNo, Date
Having Count(*)>1