在case语句中使用NOT NULL计算数字列

时间:2017-08-21 16:51:45

标签: sql-server tsql

我的查询需要一些帮助...我想在每个房子里计算一些名字,所有的col#都是名字。

查询:

SELECT 
    House#, 
    COUNT(CASE WHEN col#1 IS NOT NULL THEN 1 ELSE 0 END) +
    COUNT(CASE WHEN col#2 IS NOT NULL THEN 1 ELSE 0 END) +
    COUNT(CASE WHEN col#3 IS NOT NULL THEN 1 ELSE 0 END) AS count
FROM 
    myDB 
WHERE 
    House# IN (house#1, house#2, house#3) 
GROUP BY 
    House#

期望的结果:

house 1 - the count is 3
house 2 - the count is 2
house 3 - the count is 1

...根据我当前的查询,计数结果只是3&#39>

1 个答案:

答案 0 :(得分:1)

设计

COUNT并不算NULL个值。

SELECT House#, 
       COUNT(col1#) + COUNT(col2#) + COUNT(col3#) AS count
FROM myDB 
WHERE House# IN (house#1,house#2,house#3) 
GROUP BY House#;