Answers:
在第一种情况下,您只需简单地计算1s和NULL。(如果CASE语句中的所有条件均不匹配且没有ELSE子句,则返回NULL。)不计入NULL。在第二种情况下为1和0。可以计数为0。
快速示例:
CREATE TABLE #CountMe (Col1 char(1));
INSERT INTO #CountMe VALUES ('A');
INSERT INTO #CountMe VALUES ('B');
INSERT INTO #CountMe VALUES ('A');
INSERT INTO #CountMe VALUES ('B');
SELECT
COUNT(CASE WHEN Col1 = 'A' THEN 1 END) AS CountWithoutElse,
COUNT(CASE WHEN Col1 = 'A' THEN 1 ELSE NULL END) AS CountWithElseNull,
COUNT(CASE WHEN Col1 = 'A' THEN 1 ELSE 0 END) AS CountWithElseZero
FROM #CountMe;
输出: