SQL 服务器:条件聚合与 mysql 不同?

SQL Server : conditonal aggregation different to mysql?

我昨天发布了一个问题,Gordon Linoff 回答得很好。

基本上我使用的是 MySQL 并且需要删除 where 语句,因为它在不需要时影响所有列,条件聚合是我的答案,它与 MySQL 一起使用。

查询如下:

select 
    sum(amount) as `total amount for all items sold`,
    count(amount) as `Total items sold`,
    sum(sale_made between '2018-07-02' and '2018-07-05') as `half total days`
from
    sales; 

同样,这在 MySQL 中完美运行,但在 SQL Server 2017 中,我在这里遇到错误 '2018-07-05')

在 MySQL 表达式中,可以为真或假,求值为 1 或 0。因此 MySQL 中的 sale_made between '2018-07-02' and '2018-07-05' 可以为 1 或 0,具体取决于 [=12] =] 是否在相应的范围内。并且可以对数字 0 或 1 求和。

SQL 服务器没有将逻辑表达式转换为数字的功能。这样的表达式在任何不需要逻辑表达式的上下文中都是非法的。所以你必须用 CASE.

自己做 "translation"
CASE
  WHEN sale_made BETWEEN '2018-07-02'
                         AND '2018-07-05' THEN
    1
  ELSE
    0
END

你只需要一个case表达式:

select sum(amount) as [total amount for all items sold],
       count(amount) as [Total items sold],
       sum(case when sale_made between '2018-07-02' and '2018-07-05' then 1 else 0 end) as [half total days]
from sales; 

请注意,这还会更改列别名的转义字符。