I can brute force this, but feel like there's a more efficient way. For each group ID below, I want to return the ONE record flagged as TRUE. Or if NO record in the group is flagged as TRUE, then I want to return ALL the FALSE records. I'm using the latest version of SQL Server.
select 500 id, 100 group_id, 0 flag into #y
union select 501, 100, 0
union select 502, 100, 0
union select 503, 100, 0
union select 504, 100, 1
union select 505, 101, 0
union select 506, 101, 0
union select 507, 101, 0
union select 508, 102, 0
union select 509, 102, 1
union select 510, 102, 0
The desired results would return ID's 504 and 509 (the single TRUE record in groups 100 and 102 respectively) and ID's 505, 506, 507 (all records in group 101 because no TRUE record exists in the group).
select * from #y where id in (504, 505, 506, 507, 509)
I tried some things with subqueries and window functions but feel like there's a more straightforward way. Thank you.