gpt4 book ai didi

mysql - 获取每个月的交易余额

转载 作者:行者123 更新时间:2023-11-29 23:24:53 24 4
gpt4 key购买 nike

我得到了一个包含事务的 2 列表,其中存储了更改时间 (unix_time) 和更改值。

create table transactions (    
changed int(11),
points int(11)
);

insert into transactions values (UNIX_TIMESTAMP('2014-03-27 03:00:00'), +100);
insert into transactions values (UNIX_TIMESTAMP('2014-05-02 03:00:00'), +100);
insert into transactions values (UNIX_TIMESTAMP('2015-01-01 03:00:00'), -100);
insert into transactions values (UNIX_TIMESTAMP('2015-05-01 03:00:00'), +150);

要获得当前余额,您需要对所有值求和,而要获得过去的余额,如果该值的更改时间少于请求的时间,则需要求和,如下所示:

select 
sum(case when changed < unix_timestamp('2013-12-01') then
points
else
0
end) as cash_balance_2013_11,
...

因此每个月都需要有一个单独的 SQL 代码。我想要 SQL 代码来为我提供所有月份的余额。 (例如从固定日期到现在)

编辑:

HERE IS SQL FIDDLE

最佳答案

您可以只分组依据月份排序吗?

更新:要获得运行总计,您必须将各个月份加入到一组按月总计中,匹配“小于或等于”:-

select
m.single_month
, sum(month_of_change.total_points) as running total_by_month
from
(
select
sum(points) as total_points
, month_of_change
from
(
select
points
, MONTH(FROM_UNIXTIME(t.time_of_change)) as month_of_change -- assumes unix_time
from mytable t
) x
group by month_of_change
) monthly_totals
inner join
(
select distinct MONTH(FROM_UNIXTIME(t.time_of_change)) as single_month
) m
on monthly_totals.month_of_change <= m.single_month
group by m.single_month

(注意:未测试)

关于mysql - 获取每个月的交易余额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27046772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com