MSSQL:显示具有Case和Count的Select的行,即使Count = 0

时间:2014-04-23 13:28:53

标签: sql sql-server count case

我希望我能详细解释我的问题,所以你们可以理解我。 我创建了一个小例子。

我有一个看起来像这样的表:

City       |    Name

Berlin     |    Mike
Berlin City|    Peter
Stuttgart  |    Boris

这是我的查询:

    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

结果如下:

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

但我希望的结果是:

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

我怎样才能得到我想要的结果?希望你能帮助我。

提前致谢。

SQL Fiddle Demo

1 个答案:

答案 0 :(得分:3)

如果您没有包含城市列表的表格,则可以使用子查询。解决此类问题的关键是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;

如果您想拥有'unknown',则可以使用full outer join

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');