且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

T-SQL SUM All with a Conditional COUNT

更新时间:2023-02-06 11:22:02

你想要一个条件总和,像这样:

You want a conditional sum, something like this:

sum(case when cancelled = 'false' then 1 else 0 end)

使用sum()的原因.sum() 正在处理记录并为每条记录添加一个值,01.该值取决于cancelled 的值.当它为假时,sum() 增加 1 —— 计算这些值的数量.

The reason for using sum(). The sum() is processing the records and adding a value, either 0 or 1 for every record. The value depends on the valued of cancelled. When it is false, then the sum() increments by 1 -- counting the number of such values.

你可以用 count() 做类似的事情,像这样:

You can do something similar with count(), like this:

count(case when cancelled = 'false' then cancelled end)

这里的技巧是 count() 计算非 NULL 值的数量.then 子句可以是任何非 NULL -- cancelled、常量 1 或其他字段.如果没有 else,任何其他值都会变成 NULL 并且不计算在内.

The trick here is that count() counts the number of non-NULL values. The then clause can be anything that is not NULL -- cancelled, the constant 1, or some other field. Without an else, any other value is turned into NULL and not counted.

我一直更喜欢 sum() 版本而不是 count() 版本,因为我认为它更明确.在 SQL 的其他方言中,您有时可以将其缩短为:

I have always preferred the sum() version over the count() version, because I think it is more explicit. In other dialects of SQL, you can sometimes shorten it to:

sum(cancelled = 'false')

一旦你习惯了,就会很有意义.

which, once you get used to it, makes a lot of sense.