簡體   English   中英

行號分區

[英]row number partition

我正在使用SQL Server Management Studio 2012。

抱歉,您可能會誤導標題,不確定該如何稱呼。

我需要鍛煉如何找到僅動員了一個人的事件。 我想我可以通過使用Row_Number分區然后在1上進行過濾來實現

 RowNumber    Incident MobilisedDateTime     Name
    1          abc     2019-02-08            Fred
    2          abc     2019-02-08            Roger
    3          abc     2019-02-08            Brian
    4          abc     2019-02-08            John
    1          def     2019-02-08            Joe
    1          ghi     2019-02-07            Robert
    1          jkl     2019-02-06            Jimmy
    2          jkl     2019-02-06            John

這是對行號1進行過濾時發生的事情。這不是我要執行的操作,因為事件'abc'和'jkl'已動員了一個以上的人。

    RowNumber Incident MobilisedDateTime     Name
    1          abc     2019-02-08            Fred
    1          def     2019-02-08            Joe
    1          ghi     2019-02-07            Robert
    1          jkl     2019-02-06            Jimmy

我想看到的結果是這樣

    RowNumber Incident MobilisedDateTime     Name
     1          def     2019-02-08           Joe
     1          ghi     2019-02-07           Robert

最好的方法可能not exists 不需要窗口功能:

select t.*
from t
where not exists (select 1 
                  from t t2
                  where t2.incident = t.incident and
                        t2.name <> t.name
                 );

為了提高性能,您需要在(incident, name)上建立索引。

您可以嘗試此查詢,這將返回您的結果

select RowNumber,Incident,MobilisedDateTime,max(Name) as name,count(distinct name) as cnt from table_name group by RowNumber,Incident,MobilisedDateTime  having(count(distinct name) = 1)

暫無
暫無

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

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