0

在我的表中,我需要知道每个ID人是否只有一个ID_name。我怎样才能写这样的查询?

我试过:

select ID, count(distinct ID_name) as count_name 
from table 
group by ID 
having count_name > 1

但它需要永远运行。

有什么想法吗?

4

2 回答 2

2
select  ID
from    YourTable
group by
        ID
having  count(distinct ID_name) > 1

或者

select  *
from    YourTable yt1
where   exists
        (
        select  *
        from    YourTable yt2
        where   yt1.ID = yt2.ID
                and yt1.ID_Name <> yt2.ID_Name
        )

现在,大多数ID列都被定义为primary key并且是唯一的。因此,在常规数据库中,您希望两个查询都返回一个空集。

于 2012-11-06T17:44:01.730 回答
0

select tt.ID,max(tt.myRank) from (select ip.ID,ip.ID_name, ROW_Number() over (partition by ip.ID,ip.ID_nameorder by ip.ID) as myRank from YourTable ip) tt group by tt.ID

这为您提供了每个 ID 的 ID_Name 总数

如果您只想要那些关联多个名称的 ID,只需添加一个 where 子句,例如

select tt.ID,max(tt.myRank) from (select ip.ID,ip.ID_name, ROW_NUMBER() over (partition by ip.ID,ip.ID_nameorder by ip.ID) as myRank from YourTable ip) tt where tt .myRank > 1 组(按 tt.ID)

于 2012-11-06T18:05:37.450 回答