2012-04-23 37 views
0

我觉得这是重复的,像这样的数据库记录:查找多列重复再一一列举

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

最简单的方法是从Find-dups查询创建一个内嵌查询并加入到“不带分组”的查询中。

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 
+0

+1,这可能是最简单,最优雅的方式。 – 2012-04-23 16:41:50

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;