获取每个月的交易余额

时间:2014-11-20 18:22:57

标签: mysql sql

我有一个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

1 个答案:

答案 0 :(得分:0)

你可以group byorder by月吗?

更新:要获得正在运行的总计,您必须将每个月加入到一组总计中,匹配&#34;小于或等于&#34;: - < / p>

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

(N.B:未经测试)