计算具有非零值的列数

时间:2019-06-12 08:31:58

标签: sql

我有以下脚本,

SELECT COUNT(*) AS Total,
    SUM(CASE WHEN TypeId ='4' THEN 1 ELSE 0 END) AS 'TotalCount1', 
    SUM(CASE WHEN TypeId ='6' THEN 1 ELSE 0 END) AS 'TotalCount2', 
    SUM(CASE WHEN TypeId ='1' THEN 1 ELSE 0 END) AS 'TotalCount3', 
    SUM(CASE WHEN TypeId ='10' THEN 1 ELSE 0 END) AS 'TotalCount4', 
    SUM(CASE WHEN TypeId ='5' THEN 1 ELSE 0 END)  AS 'TotalCount5', 
    SUM(CASE WHEN TypeId ='8' THEN 1 ELSE 0 END)  AS 'TotalCount6' 
    FROM [Party]

请将屏幕截图作为上述脚本的输出。

我想要什么: 我想要“总计”之后的列为具有非零值的列的总数。 就像图片中一样,该值应为2,因为TotalCount1和Totalcount3的值均为非零。

enter image description here

2 个答案:

答案 0 :(得分:0)

在选择结果上使用CASE表达式,您可以这样做:

SELECT (
    CASE WHEN TotalCount1 > 0 THEN 1 ELSE 0 END + 
    CASE WHEN TotalCount2 > 0 THEN 1 ELSE 0 END + 
    CASE WHEN TotalCount3 > 0 THEN 1 ELSE 0 END + 
    CASE WHEN TotalCount4 > 0 THEN 1 ELSE 0 END + 
    CASE WHEN TotalCount5 > 0 THEN 1 ELSE 0 END + 
    CASE WHEN TotalCount6 > 0 THEN 1 ELSE 0 END) AS Result 
FROM (
SELECT COUNT(*) AS Total,
    SUM(CASE WHEN TypeId ='4' THEN 1 ELSE 0 END) AS 'TotalCount1', 
    SUM(CASE WHEN TypeId ='6' THEN 1 ELSE 0 END) AS 'TotalCount2', 
    SUM(CASE WHEN TypeId ='1' THEN 1 ELSE 0 END) AS 'TotalCount3', 
    SUM(CASE WHEN TypeId ='10' THEN 1 ELSE 0 END) AS 'TotalCount4', 
    SUM(CASE WHEN TypeId ='5' THEN 1 ELSE 0 END)  AS 'TotalCount5', 
    SUM(CASE WHEN TypeId ='8' THEN 1 ELSE 0 END)  AS 'TotalCount6' 
FROM [Party]
) A

答案 1 :(得分:0)

SELECT COUNT(*) AS Total,
       ...
       ... 
       CASE ( WHEN SUM(CASE WHEN TypeId ='4' THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END) +  
       CASE ( WHEN SUM(CASE WHEN TypeId ='6' THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END) + 
       CASE ( WHEN SUM(CASE WHEN TypeId ='1' THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END) + 
       CASE ( WHEN SUM(CASE WHEN TypeId ='10' THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END) + 
       CASE ( WHEN SUM(CASE WHEN TypeId ='5' THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END) + 
       CASE ( WHEN SUM(CASE WHEN TypeId ='8' THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END)  
          as SumOfNonZeros

FROM [Party]

或更简单

SELECT COUNT(*) AS Total,
       COUNT(CASE WHEN TypeId ='4'  THEN 1 END) AS 'TotalCount1', 
       COUNT(CASE WHEN TypeId ='6'  THEN 1 END) AS 'TotalCount2', 
       COUNT(CASE WHEN TypeId ='1'  THEN 1 END) AS 'TotalCount3', 
       COUNT(CASE WHEN TypeId ='10' THEN 1 END) AS 'TotalCount4', 
       COUNT(CASE WHEN TypeId ='5'  THEN 1 END) AS 'TotalCount5', 
       COUNT(CASE WHEN TypeId ='8'  THEN 1 END) AS 'TotalCount6',
       COUNT( DISTINCT CASE WHEN TypeId IN ('4', '6', '1', '10', '5', '8') 
                            THEN TypeId 
                       END ) as CountOfNonZeros
FROM [Party]