Mysql 计算多个 SUM() 变量

Posted

技术标签:

【中文标题】Mysql 计算多个 SUM() 变量【英文标题】:Mysql calculate multiple SUM() varialbe 【发布时间】:2020-09-05 12:55:27 【问题描述】:

我想计算 2 sum() 我已经尝试过如下查询,它可以工作但速度很慢。有什么想法可以让它变得更好吗?

SELECT customer, 
       SUM(CASE WHEN book_day BETWEEN '2020-01-01' AND '2020-01-31'  
                THEN pax+free 
                ELSE 0 
                END) AS January,
       SUM(CASE WHEN book_day BETWEEN '2020-02-01' AND '2020-02-31'  
                THEN pax+free 
                ELSE 0 
                END) AS February,
       ( SUM(CASE WHEN book_day BETWEEN '2020-01-01' AND '2020-01-31'  
                  THEN pax+free 
                  ELSE 0 
                  END) + 
         SUM(CASE WHEN book_day BETWEEN '2020-02-01' AND '2020-02-31'  
                  THEN pax+free 
                  ELSE 0 
                  END) ) AS total
 FROM rezervations  

我怎样才能让January + February as total这样更简单

【问题讨论】:

'2020-02-31' 匹配无效日期。顺便说一句,book_day 列上是否有索引..? 它只是看起来是否存在一天,不管我寄给他什么。只关注查询:) 好吧,那就使用SUM(CASE WHEN book_day BETWEEN '2020-01-01' AND '2020-02-29' THEN pax+free ELSE 0 END AS total,但不要检查索引是否存在性能问题。 @AliGüzel 下面的查询将运行得更快,因为book_day 上有一个索引 不知book_days列的格式是DATE,还是DATE... 【参考方案1】:

BETWEEN '2020-01-01' AND '2020-02-29' 保留在 where 子句中。

确保 book_day 列上有索引

SELECT customer, 
SUM(CASE WHEN book_day BETWEEN '2020-01-01' AND '2020-01-31' THEN pax+free ELSE 0 END) as January,
SUM(CASE WHEN book_day BETWEEN '2020-02-01' AND '2020-02-29'  THEN pax+free ELSE 0 END) as February,
(SUM(CASE WHEN book_day BETWEEN '2020-01-01' AND '2020-02-29'  THEN pax+free ELSE 0 END) ) as total
 FROM rezervations 
WHERE
book_day BETWEEN '2020-01-01' AND '2020-02-29'

【讨论】:

以上是关于Mysql 计算多个 SUM() 变量的主要内容,如果未能解决你的问题,请参考以下文章

如何计算mysql中多个条件值的总和

多个 SUM 的 MySQL 子查询

MYSQL 更新使用 sum() 结果跨多个表

如何对mysql中多个表的字段求和?

在 mysql 中使用 SUM 和多个连接

跨 MYSQL 中的多个列选择 SUM(DISTINCT 值)