I'm using 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
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.
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
. 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)
.
您可以尝试此查询,这将返回您的结果
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.