2

is there option to set "default" values to groupBy?

For example I have column cars where values are inserted from enum (BMW, Porsche, Audi itd.).

I would like to group by and count this cars:

select brand, count(*)
from cars
group by brand

If there are values with all of this enum in database, then its ok - results are like this:

BMW | 3
Audi | 4
Jaguar | 5

But if I have in database only cars with BMW result is only BMW:

BMW | 3

and there is my question - how to add default fields to have response like:

BMW | 3
Audi | 0
Mercedes | 0

1 Answer 1

1

You need to list the values somehow. One method uses a values clause:

select brand, count(c.brand)
from (values ('BMW'), ('Audi'), ('Jaguar')) v(brand) left join
     cars c
     using (brand)
group by brand;

In practice, you should have the brands in their own table, so you could use:

select brand, count(c.brand)
from brands b
     cars c
     using (brand)
group by brand;
Sign up to request clarification or add additional context in comments.

1 Comment

What in the world is v(brand)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.