T-SQL SUM All with a Conditional COUNT

前端 未结 1 1408
[愿得一人]
[愿得一人] 2021-01-23 12:44

I have a query that produces the following:

Team  | Member  |  Cancelled | Rate
-----------------------------------
  1     John         FALSE      150
  1     B         


        
相关标签:
1条回答
  • 2021-01-23 13:35

    You want a conditional sum, something like this:

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

    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.

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

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

    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.

    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.

    0 讨论(0)
提交回复
热议问题