Search code examples
sqlsql-serversql-server-2016

Selecting one vs all records within group in SQL Server


I have a table in SQL Server something like this (these records are coming from user input later I have to join this table with business table)

Table A

id group item
1 A 4567876
2 A 5678988
3 A 9999999
4 B 1234567
5 B 6846677

For each group I want to select, If there is any entry for item 9999999 then select only this record else all records in that respective group. (e.g for given example in group A select item 9999999 and for group B all items)

id group item
3 A 9999999
4 B 1234567
5 B 6846677

I don't want to delete any records from the table.


Solution

  • You can use not exists:

    select a.*
    from a
    where a.item = 9999999 or
          not exists (select 1
                      from a a2
                      where a2.group = a.group and
                            a2.item = 9999999
                     );
    

    You can also use a fancy trick with rank():

    select top (1) with ties t.*
    from t
    order by rank() over (partition by group
                          order by (case when item = 9999999 then 1 else 2 end)
                         );