How to filter columns with multiple values for each ID in SQL Server

106 views Asked by At

I have a result set as below and I want to select a single record when the same ID has 2 records with different values for Age and status column, for example

Please see the result set below where ID, name, country name coming from table A and Age, Active status coming from b table

ID  name  country Age                  status 
----------------------------------------------
1  Prasad India   NULL                  NULL 
2  John   USA     NULL                  NULL 
3  GREG   AUS     NULL                  NULL 
4  RAVI   India   NULL                  NULL 
4  RAVI   India   18 Years and Above     1
1

There are 1 answers

0
zip On BEST ANSWER

Go with this:

    Select * 
    From 
(
    Select t2.*, 
    ROW_NUMBER() over(partition by ID order by name,country,Age, status desc) as rn
    From yourtable t2
)
Where rn = 1