Reputation: 2713
I have the schema built at this SQL Fiddle if you want to try out.
I have the following data
AutoID Apartment Flag Description
====== ========= ==== ===========
1 1 NO Device 1
2 1 NO Device 2
3 1 NO Device 3
4 2 NO Device 4
5 2 NO Device 5
6 3 NO Device 6
7 3 NO Device 7
8 3 YES Device 8
9 3 NO Device 9
I'm trying to get the data with the following rule
So if I run the SQL statement I would end up with
AutoID Apartment Flag Description
====== ========= ==== ===========
1 1 NO Device 1
4 2 NO Device 4
8 3 YES Device 8
I've been trying to play around with OVER() and PARTITION BY with little luck. Any help or guidance is greatly appreciated.
Upvotes: 4
Views: 2319
Reputation: 4684
First step - assign order numbers in each group with the same apartment number
Second step - select only the first one
select AutoID, Apartment, Flag, Description from (
select AutoID, Apartment, Flag, Description, row_number() over (partition by apartment order by Flag desc) rnum
from table1)
where rnum = 1
Upvotes: 2