简体   繁体   English

行号分区

[英]row number partition

I'm using SQL Server Management Studio 2012. 我正在使用SQL Server Management Studio 2012。

Sorry for the potentially misleading title wasn't sure what to call it. 抱歉,您可能会误导标题,不确定该如何称呼。

I need to workout how to find Incidents where only one Person has been mobilised to it. 我需要锻炼如何找到仅动员了一个人的事件。 I figured I'd be able to achieve this by using Row_Number partition and then filtering on 1 我想我可以通过使用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

This is what happens when filtering on row number 1. This is not what I'm after because Incident 'abc' and 'jkl' had more than one person mobilised to it. 这是对行号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

The result I would like to see is this 我想看到的结果是这样

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

The best method is probably not exists . 最好的方法可能not exists Window functions are not needed: 不需要窗口功能:

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

For performance, you want an index on (incident, 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