Skip to content
Advertisement

For the GROUP BY function in PostgreSQL, how to set a value if any rows meet a condition?

I have a use case that needs to set a value if any rows meet a condition in the GROUP BY function of PostgreSQL. The example is as following. The table contains the following data.

id, type
1,  A
1,  B
1,  A
2,  B
2,  B

I want to run the SQL query to group by based on id. If any rows of the same id have type as ‘A’, then the resultant type after group by should be ‘A’ for this id. Otherwise, it should be ‘B’.

So I want to the result as below.

1, A
2, B

How should I prepare the SQL statement for this use case?

Thanks!

Advertisement

Answer

You can just use distinct on:

select distinct on (id) t.*
from t
order by id, type;

This uses the logic that 'A' < 'B'. You can be more explicit with something like:

select distinct on (id) t.*
from t
order by id, (type = 'A') desc;

One way to express this as aggregation is:

select id, min(type)
from t
group by id;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement