Display zero by using count(*) if no result returned for a particular case

后端 未结 2 948
执笔经年
执笔经年 2021-01-02 20:10

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         


        
相关标签:
2条回答
  • 2021-01-02 20:14

    The problem is that you are grouping by edition_id. If there is no edition_id in your result then it can't count it.

    What you can do instead is select all the cities out with their edition id, left join it to the counts and then do an 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
    
    0 讨论(0)
  • 2021-01-02 20:25

    I would insert the cities into a temporary table, then do a LEFT JOIN with the grouping query as follows:

    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
    

    BTW, it would make sense to have #cities as a normal table so that you don't need to create it everytime the query runs.

    0 讨论(0)
提交回复
热议问题