i’m trying to create a query that allows me to get 2 counts from selects.
I have a table (name "warehouses") with the following design and data:
nation | city |
---|---|
italy | roma |
germany | berlin |
italy | roma |
france | paris |
italy | torino |
italy | firenze |
I would like to get the count of nation and the related count of city
example:
nation: italy 4
city: roma 2
nation: italy 4
city: torino 1
nation: italy 4
city: firenze 1
my attempt
select nation, city, count (nation), count (city)
from warehouses
but result is different than I would like…
select nation, city, count (nation), count (city)
from warehouses
2
Answers
The easiest approch to get both city and country counts is to use
WITH ROLLUP
:If you want to suppress the full total and want the nation total before the city totals, add a
HAVING
clause and change theORDER BY
clause.Or with
COALESCE
for a single nation-or-city column:select
coalesce(city, nation) as name,
count(*)
from warehouses
group by nation, city with rollup
having nation is not null
order by nation, city is not null, city;
Demo: https://dbfiddle.uk/4HERVYak