Simon Osipov
Simon Osipov

Reputation: 424

SQL Group By, case when on aggregated

Can't wrap my mind around the next task: I have a table, with some key, which represents some kind of group id. I would like to GROUP BY by this key and in resulted table show some columns from this table depending on the column value: If all the values in this group by this key in col1 are equal (same number or text), then show this exact value, if they are different (at least one of them) - show some kind like "Others".

Example

key col1
1     1
1     1
1     1
2     4
2     5

Resulted table:

key col1
1     1
2     Others

Postgres 9.4, if this matters.

Upvotes: 0

Views: 92

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269463

You can use aggregation and case:

select key,
       (case when min(col1) = max(col1) then min(col1)
             else 'others'
        end) as col1
from t
group by key;

Upvotes: 4

Related Questions