Sql-server – select single row from table for a particular column combination

selectsql server

I have a table as below

Id… ColA… ColB… Isdefault


1… 100… 96… 1
2… 100… 96… 0
3… 101… 98… 0
4… 102… 99… 1

I want to have a select statement, where for a particular combination of ColA and ColB, I should get only one Row with the condition that if Isdefault with values both 0 and 1 present for a particular ColA,ColB combination, I should Only select one row with Isdefault=1 .

The output should look like below:

Id… ColA… ColB… Isdefault


1… 100… 96… 1
3… 101… 98… 0
4… 102… 99… 1

Note: Row with Id=2 is not present in the output because the same combination of ColA and ColB exists with isdefault=1

kindly help, thanx in advance.

Best Answer

declare @t table(Id int, ColA int, ColB int, Isdefault bit);
insert into @t values
(1, 100, 96, 1),
(2, 100, 96, 0),
(3, 101, 98, 0),
(4, 102, 99, 1);

with cte as
(
select *, row_number() over(partition by ColA, ColB order by Isdefault desc) rn
from @t
)

select Id, ColA, ColB, Isdefault
from cte
where rn = 1;