簡體   English   中英

SQL查詢:如何通過另一列區分列組的計數

[英]SQL query: how to distinct count of a column group by another column

在我的表中,我需要知道每個ID是否只有一個ID_name 我怎樣才能寫這樣的查詢?

我試過了:

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

但它需要永遠運行。

有什么想法嗎?

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並且是唯一的。 因此,在常規數據庫中,您希望兩個查詢都返回一個空集。

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**
group by tt.ID

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM