使用多个日期范围设置多个和

332nm8kg  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(359)

这是我试图完成的查询。

SELECT salesrep, 
    SUM(lines_total) AS OTSUM,
    SUM(order_type = 'NEW') OTNEW,
    SUM(order_type = 'REPEAT') OTREPEAT,
    SUM(lines_total 
      WHERE order_closed BETWEEN '2020-11-01' AND '2020-11-30') AS OTLMSUM
    SUM(lines_total 
      WHERE order_closed BETWEEN '2020-12-01' AND '2020-12-31') AS OTTMSUM
FROM `ranger_orders`
WHERE order_closed BETWEEN '2020-01-01' AND '2020-12-31'

当然失败了,但是如何设置多个日期范围的总和,末尾的where日期范围需要保持原样。
对于这些行:

SUM(lines_total WHERE order_closed BETWEEN '2020-11-01' AND '2020-11-30') AS OTLMSUM
SUM(lines_total WHERE order_closed BETWEEN '2020-12-01' AND '2020-12-31') AS OTTMSUM
gdrx4gfi

gdrx4gfi1#

要按salesrep保持数据在行上对齐,那么您仍然需要添加所有的数字-但是您可以在它们超出范围的地方用零替换。。。。

SUM(IF (order_closed BETWEEN '2020-11-01' AND '2020-11-30', lines_total, 0)) AS OTLMSUM

您指出出现语法错误,但这看起来像是语义错误:

SUM(order_type = 'NEW') OTNEW

你真的想把这些加起来吗?数一数?把它们分类?
查询可能类似于。。。

SELECT salesrep, 
    SUM(lines_total) AS OTSUM,
    SUM(IF(order_type = 'NEW', 1, 0)) OTNEW,
    SUM(IF(order_type = 'REPEAT', 1, 0)) OTREPEAT,
    SUM(IF (order_closed BETWEEN '2020-11-01' AND '2020-11-30', lines_total, 0)) AS OTLMSUM
    SUM(if(order_closed BETWEEN '2020-12-01' AND '2020-12-31', lines_total, 0)) AS OTTMSUM
FROM `ranger_orders`
WHERE order_closed BETWEEN '2020-01-01' AND '2020-12-31'

另外,对于聚合查询(sum、average、count…),应该有一个groupby子句。。。。

GROUP BY salesrep

然而,这样做不是更简单吗。。。。

SELECT salesrep, 
    SUM(lines_total) AS OTSUM,
    SUM(IF(order_type = 'NEW', 1, 0)) AS OTNEW,
    SUM(IF(order_type = 'REPEAT', 1, 0)) AS OTREPEAT,
    DATE_FORMAT(order_closed, '%Y-%m') AS month,
    SUM(lines_total) AS otsum
FROM `ranger_orders`
WHERE order_closed BETWEEN '2020-01-01' AND '2020-12-31'
GROUP BY salesrep, DATE_FORMAT(order_closed, '%Y-%m')
ycggw6v2

ycggw6v22#

你需要 CASE 条件聚合的表达式,如:

SUM(CASE WHEN order_closed BETWEEN '2020-12-01' AND '2020-12-31' THEN lines_total ELSE 0 END) AS OTTMSUM

对于每一个和,改变 BETWEEN '2020-12-01' AND '2020-12-31' 相应地。

相关问题