2014-11-20 85 views
0

我收到了一個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

+0

你可以分成這裏的時間間隔 http://stackoverflow.com/questions/4342370/grouping-into-interval-of-5-minutes-within-a-time-range – 2014-11-20 18:28:53

+0

@ Horst Walter:據我所知,這會在一個月內給我帶來改變。爲了獲得平衡,您不僅需要從給定的月份中總結所有以前的值。 – Pueblo 2014-11-20 18:44:13

回答

0

你能只是group byorder by一個月?

UPDATE:獲得運行總和,你必須參加個別月份的一組總計按一個月,在「小於或等於」匹配: -

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 

(NB:沒有測試過)

+0

據我所知,這會在一個月內給我帶來改變。爲了獲得平衡,您不僅需要從給定的月份中總結所有以前的值。 – Pueblo 2014-11-20 18:43:48

+0

有趣,但我的大腦在第三個子查詢後溢出,所以我需要檢查這個。我無法投票給你,因爲我沒有足夠的聲譽,對不起。 – Pueblo 2014-11-20 19:00:47

+0

我無法完成工作。我更新了我的問題,使其更加清晰。 – Pueblo 2015-03-19 19:45:05