6

I have a query like this that returns number of rows for each case in city .

select 
    case edition_id 
        when 6 then 'DELHI' 
        when 50 then 'AHMEDABAD' 
        when 4 then 'HYDERABAD' 
        when 25 then 'KOLKATA' 
        when 51 then 'BANGALORE' 
        when 5 then 'MUMBAI' 
        when 24 then 'CHENNAI' 
    end as CITY,
    count(*) as Total 
from #tmptab1
group by edition_id

drop table #tmptab1

The result comes out to be like

CITY    Total
MUMBAI  1
DELHI   28
CHENNAI 1
KOLKATA 35
AHMEDABAD 3

So if there is no rows returned from a city , that city is omitted in final result

I want result as

CITY    Total
MUMBAI  1
DELHI   28
CHENNAI 1
KOLKATA 35
AHMEDABAD 3
BANGALORE 0 -- if no result from bangalore display zero.

How to do this ?

I tried

case count(*)>0 then count(*) else 0 end as Total 

but it does not work

4

2 回答 2

6

我会将城市插入到临时表中,然后使用分组查询执行 LEFT JOIN,如下所示:

CREATE TABLE #cities (edition_id INT, city VARCHAR(16))
INSERT INTO #cities VALUES(6, 'DELHI')
INSERT INTO #cities VALUES(50, 'AHMEDABAD')
INSERT INTO #cities VALUES(4, 'HYDERABAD')
INSERT INTO #cities VALUES(25, 'KOLKATA')
INSERT INTO #cities VALUES(51, 'BANGALORE')
INSERT INTO #cities VALUES(5, 'MUMBAI')
INSERT INTO #cities VALUES(24, 'CHENNAI')

select 
    c.city 'City', 
    ISNULL(t.Total, 0) 'Total'
from 
    #cities c
    LEFT JOIN (
        SELECT 
            edition_id, count(*) as Total 
        #tmptab1 
        GROUP BY edition_id
    ) AS t
    ON c.edition_id = t.edition_id

drop table #tmptab1
drop table #cities

顺便说一句,将其作为普通表是有意义的,#cities这样您就不需要在每次查询运行时都创建它。

于 2012-12-20T05:14:41.300 回答
3

问题是您按 edition_id 分组。如果您的结果中没有 edition_id,则无法计算。

您可以做的是选择所有带有版本 ID 的城市,将其加入计数,然后执行 isnull:

WITH CITIES AS
(
        SELECT 6 AS edition_id, 'DELHI' As CityName
        UNION
        SELECT 50, 'AHMEDABAD'
        UNION
        ....
)
SELECT c.cityname, isnull(counts.total,0) as total
FROM CITIES
LEFT JOIN (SELECT edition_id, count(*) as Total #tmptab1 group by edition_id) counts ON counts.edition_id = CITIES.edition_id
于 2012-12-20T05:17:51.073 回答