关于CASE WHEN的多条件汇总问题

https://bbs.csdn.net/topics/392217817?page=1

问题:

--创建测试表
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TB]') AND type in (N'U'))
DROP TABLE [dbo].[TB1]
GO
CREATE TABLE [dbo].[TB1](
    [卡状态] [nvarchar] (20) NULL,
    [卡类型] [nvarchar](50) NULL,
) ON [PRIMARY]
GO
 
--插入测试数据
INSERT INTO [TB1] ([卡状态],[卡类型]) 
    SELECT N'发卡',N'正式卡' UNION ALL
    SELECT N'发卡',N'正式卡' UNION ALL
    SELECT N'发卡',N'临式卡' UNION ALL
    SELECT N'制卡',N'临式卡' UNION ALL
    SELECT N'制卡',N'正式卡'
GO
 
SELECT * FROM TB1

 

 回帖:

SELECT  卡状态 + '' ,
        COUNT(1) AS 总数 ,
        SUM(CASE WHEN 卡类型 = '正式卡' THEN 1
                 ELSE 0
            END) AS 正式卡 ,
        SUM(CASE WHEN 卡类型 = '临式卡' THEN 1
                 ELSE 0
            END) AS 临式卡
FROM    TB1
GROUP BY 卡状态

 

 

posted @ 2018-06-01 11:22  习惯沉淀  阅读(1385)  评论(0编辑  收藏  举报