具有日期范围条件的 Group By 和 SUM 的 sql

Posted

技术标签:

【中文标题】具有日期范围条件的 Group By 和 SUM 的 sql【英文标题】:sql for Group By and SUM with date range condition 【发布时间】:2021-11-10 08:35:40 【问题描述】:

下面是Invoices 表:

我正在尝试创建一个 sql 查询,它根据due_date 范围和balance_amount group by company_id 的总和为我提供输出

我的尝试:

select invoices.company_id,
SUM(invoices_cmonth.balance_amount) as cmonth,
SUM(invoices_1month.balance_amount) as 1month,
SUM(invoices_2month.balance_amount) as 2month
from `invoices` 
LEFT JOIN invoices invoices_cmonth 
ON (invoices.company_id = invoices_cmonth.company_id and invoices_cmonth.due_date >= '2021-11-10') 
LEFT JOIN invoices invoices_1month 
ON (invoices.company_id = invoices_1month.company_id and invoices_1month.due_date < '2021-11-10' and invoices_1month.due_date >= '2021-10-10')
LEFT JOIN invoices invoices_2month 
ON (invoices.company_id = invoices_2month.company_id and invoices_2month.due_date < '2021-10-10' and invoices_2month.due_date >= '2021-9-10')
where invoices.`status` = 'ACTIVE' 
and invoices.`balance_amount` > 0 
and `invoices`.`deleted_at` is null 
group by invoices.`company_id`

但它给了我错误的余额数字。

【问题讨论】:

【参考方案1】:

我建议对各种时间窗口使用条件聚合对invoices 表进行一次传递:

SELECT
    company_id,
    SUM(CASE WHEN due_date >= '2021-11-10' THEN balance_amount ELSE 0 END) AS cmonth,
    SUM(CASE WHEN due_date >= '2021-10-10' AND due_date < '2021-11-10'
             THEN balance_amount ELSE 0 END) AS 1month,
    SUM(CASE WHEN due_date >= '2021-09-10' AND due_date < '2021-10-10'
             THEN balance_amount ELSE 0 END) AS 2month
FROM invoices
WHERE
    status = 'ACTIVE' AND balance_amount > 0 AND deleted_at IS NULL
GROUP BY
    company_id;

【讨论】:

看起来很完美,直到现在我测试了它。只是一个查询。是否可以在末尾添加一个 total 列,它是所有日期范围窗口的总和? 是的,将SUM(CASE WHEN due_date &gt;= '2021-09-10' THEN balance_amount ELSE 0 END) AS all_months 添加到select 子句中。

以上是关于具有日期范围条件的 Group By 和 SUM 的 sql的主要内容,如果未能解决你的问题,请参考以下文章

GROUP BY和HAVING 以及mysql中常用的日期函数

Excel VBA SQL UNION SUM 对具有不同列名的表进行 GROUP BY

MySQL 条件 SUM 使用 GROUP BY 和 DISTINCT

SQLITE 每月使用 SUM 查询 GROUP BY

复合类型数组上的 SUM 和 GROUP BY

如何连接具有不同 GROUP BY 级别的两个查询,使一些记录为空