mysqli-->是否可以创建一个查询来计算日期之间的总和

7nbnzgx9  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(232)

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

ID | user | date | balance

我想知道是否有可能按用户对下列情况之间的日期的列余额组求和:
从今天到今天+30天
从今天+31天到今天+60天
今天以上+61天
查询:

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

可能不可能在同一个查询中完成所有这些操作。如果没有,我可以执行三个单独的查询并填充一个数组。
谢谢你的帮助!

bksxznpy

bksxznpy1#

似乎您需要条件聚合:

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 (顺便说一句,这是一个mysql关键字,因此不是一个好的列名选择),另外3列包含 balance 对于三个不同的 date 范围。

相关问题