2

我在Case语句中使用多个And时遇到问题。

我的数据库看起来像:

Enrollment      Paperless      Validated
0               1              0
1               0              1
0               1              0
1               1              1
0               0              0
0               1              0
0               0              0
0               1              0
1               1              1
0               1              0

所以我的查询看起来像这样:

Select
    Count(case when [Enrollment] = 1 and [Paperless] = 1 and [Validated] = 1 then 1 else 0 end) as [Paperless]
    ,Count(case when [Enrollment] = 1 and [Paperless] = 1 and [Validated] = 1 then 1 else 0 end) as [Online_Only]
    ,Count(*) as "Total"
FROM [my_table]

Sql 小提琴:http ://sqlfiddle.com/#!3/61202/5

正如您从 sql fiddle 中看到的那样,当它们应该不同时,case 语句中的计数始终为 20。我只是在我的案例陈述中做错了什么,还是我必须在子查询中做错事?

戴夫

4

2 回答 2

6

COUNT无论实际值如何,都返回 true。所以使用:

SUM(CASE ...)

代替

COUNT(CASE ...)
于 2012-05-21T18:02:22.673 回答
2

以下是另外两种选择:

(1) 可以使用 COUNT(),但删除 ELSE 子句。这将导致 NULL 而不是 0,因此它们不会被计算在内。

(2) 也可以切换到数学运算:

SELECT SUM(Enrollment*Paperless*Validated) as <whatever>,
       SUM(Enrollment*(1-PaperLess)*Validated) as <something else>

Personally, I often like the multiplication form, because the statement is shorter and I can more often see all the conditions without scrolling.

于 2012-05-21T18:11:35.170 回答