【问题标题】:mySQLi --> Is it possible to create a query that would calculate the sum between datesmySQLi --> 是否可以创建一个查询来计算日期之间的总和
【发布时间】:2020-09-07 12:57:38
【问题描述】:

我有一个 mySQL 表,其中至少包含以下字段:

ID | user | date | balance

我想知道是否可以按用户对介于以下情况之间的日期的列余额组求和:

  • TODAY 和 TODAY + 30 天之间
  • TODAY+31 天和 TODAY+60 天之间
  • TODAY+61 天以上

查询:

SELECT user, SUM(balance) AS sumBalance
FROM table
WHERE ... CASE << this is where I think I need help...
GROUP BY user

可能不可能一次完成所有相同的查询。如果没有,我可以执行三个单独的查询并填充一个数组。

感谢您的帮助!

【问题讨论】:

标签: mysql sql date group-by sum


【解决方案1】:

您似乎想要条件聚合:

select 
    user,
    sum(case when date between current_date and current_date + interval 30 day then balance end) balance1,
    sum(case when date between current_date + interval 31 day and current_date + interval 60 day then balance end) balance2,
    sum(case when date >= current_date + interval 61 day then balance end) balance3
from mytable
where date >= current_date
group by user

这为每个 user 提供了一条记录(顺便说一下,它是 a MySQL keyword,因此对于列名来说不是一个好的选择),另外还有 3 列包含三个 balance 的总和不同的date 范围。

【讨论】:

    猜你喜欢
    • 2022-10-20
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 2013-11-10
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    相关资源
    最近更新 更多