Question

i hope i can explain my Problem in detail, so you guys can understand me. Ive created a small example.

I have a Table which looks like this:

City       |    Name

Berlin     |    Mike
Berlin City|    Peter
Stuttgart  |    Boris

here is my Query:

    SELECT CASE
            WHEN City like '%Berlin%' THEN 'Count Person in Berlin:'
            WHEN City like '%Stuttgart%' THEN 'Count Person in Stuttgart:'
            WHEN City like '%Dresden%' THEN  'Count Person in Dresden:'
            ELSE 'unknown'
            END AS Text,
            COUNT(Name) AS countPersons
     FROM tblTest
     GROUP BY City

This is the result:

Count Person in Berlin:     2
Count Person in Stuttgart:  1

But my desired result is:

Count Person in Berlin:     2
Count Person in Stuttgart:  1
Count Person in Dresden:    0

how can i get my desired result? hope you can help me.

Thanks in advance.

SQL Fiddle Demo

Was it helpful?

Solution

If you don't have a table with the list of cities, then you can use a subquery. The key to solving this type of problem is left outer join:

select cities.city, count(t.city) as numpeople
from (select 'Berlin' as city union all
      select 'Stuttgart' union all
      select 'Dresden'
     ) cities left outer join
     tbltest t
     on t.city = cities.city
group by cities.city;

If you want to have 'unknown' as well, then full outer join can be used:

select coalesce(cities.city, 'unknown') as city, count(t.city) as numpeople
from (select 'Berlin' as city union all
      select 'Stuttgart' union all
      select 'Dresden'
     ) cities full outer join
     tbltest t
     on t.city = cities.city
group by coalesce(cities.city, 'unknown');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top