SQL – Select rows based on a hierarchy of conditions

sql

It would be great if there was a POSITIVE answer to this question…

Is it possible to make an SQL selection based on an order of possible condition values.

Eg.

Rows
ID Type
2  Dog
2  Cat
4  Cat
5  Cat

As you can see the IDs of the 1st 2 rows are the same. So I would like to select 1 row per group in order of preference, therefore "Dog" first. If "Dog" doesn't exists, then select "Cat"

E.G.

SELECT ID, Type
FROM pets
WHERE Type = "Dog, Cat"
GROUP BY ID

Results would be…

ID Type
2  Dog
4  Cat
5  Cat

Best Answer

I'm fully agree with answer of Rax Olgud. Also can add hint to use ROW_NUMBER function with partition syntax - you get possibility to write more complex condition (then MAX(Type) . Then in WHERE section just filter records by rownum_alias = 1

Update:

select * from (
select ID, Type, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Type DESC) rn
FROM #temp
) a where rn = 1

In contradiction to GROUP BY solution this allows to place any columns in select statement (not only grouping)