找到多个列重复项然后将它们全部列出

时间:2012-04-23 16:29:45

标签: sql sql-server

我发现像这样重复的数据库记录:

select s.name, r.name Region, c.name Country
from supplier s
join region r on r.id = s.regionid
join region c on c.id = isnull(r.pid, r.id)
group by s.name, r.name, c.name
having count(s.name) >1 

最好的方法是将它们全部列出(所以如果两个重复它会出现两次等等)

2 个答案:

答案 0 :(得分:2)

最简单的方法是从Find-dups查询创建内联查询,然后加入“without-a-group-by”查询。

select s.name, r.name Region, c.name Country
     from supplier s
     join region r on r.id = s.regionid
     join region c on c.id = isnull(r.pid, r.id)
     inner join (select s.name, r.name Region, c.name Country
                from supplier s
                join region r on r.id = s.regionid
                join region c on c.id = isnull(r.pid, r.id)
                group by s.name, r.name, c.name
                having count(s.name) >1 ) dups
     ON s.name = dups.name
        and r.name = dups.region
        and c.name = dups.country

答案 1 :(得分:2)

我认为应该这样做:

with C as (
  select
    s.name,
    r.name Region,
    c.name Country,
    count(*) over (
      partition by s.name, r.name, c.name
    ) as ct
  from supplier s
  join region r on r.id = s.regionid
  join region c on c.id = isnull(r.pid, r.id)
)
  select
    name, Region, Country
  from C
  where ct > 1;