如何显示类别名称和总数

时间:2016-04-21 16:30:41

标签: sql sql-server tsql

如果状态1没有匹配的行,但我仍想将类别名称和总数显示为0。 我该如何修改下面的SQL?谢谢!

SELECT 
     CASE WHEN STATUS=1 THEN 'CATEGORY A' else 'CATEGORY B' end as [Category Name],
     COUNT(*) as [Total Number in Each Category]
FROM TABLE
WHERE STATUS IN (1,2) 

1 个答案:

答案 0 :(得分:1)

使用CTE(或临时表,如果您愿意)中的原始查询与空白值联合,然后从CTE查询总和:

with cte as (SELECT case WHEN STATUS=1 THEN 'CATEGORY A' else 'CATEGORY B' end as [Category Name]
                    ,COUNT(*) as [Total Number in Each Category]
            FROM TABLE
            WHERE STATUS IN (1,2)
            UNION ALL
            select  'CATEGORY A' as [Category Name]
                    ,0 as [Total Number in Each Category]
            UNION ALL
            select  'CATEGORY B' as [Category Name]
                    ,0 as [Total Number in Each Category])

select [Category Name]
        , sum([Total Number in Each Category]) as [Total Number in Each Category]
from CTE
group by [Category Name]