Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

GROUP BY except for specific values that need to be added up

I have a table like this:

id | type
---+------
1  | plane
2  | plane
3  | ferry
4  | ferry
5  | car
6  | car
7  | bus
8  | train

We can count the rows for each type:

select type, count(*) from transport group by type;

type  | count
------+------
plane | 2
ferry | 2
car   | 2
bus   | 1
train | 1

This works, but notice how the last three types – car, bus, train – are ground transport (while plane is air and ferry is sea). What I really want is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type   | count
-------+------
plane  | 2
ferry  | 2
car    | 4

I could sum up the counts at the application level, but is this feasible in SQL? Thank you.

>Solution :

You can use a case expression to reassign buses and trains to the car group:

select
    case when type in ('bus', 'train') then 'car' else type end as new_type,
    count(*)
from transport
group by new_type
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading