每个帐户每个日期的运行差异

时间:2018-04-20 05:20:52

标签: mysql

account  Debit_Balance    Long       Short      Date         Daily_Change (Expected) 
716-05    18981100       27946000   8964860   4/10/2018         0
716-06    -7526070       1676250    9202320   4/10/2018         0
716-07    6596930        26579600   19982700  4/10/2018         0
716-11    -1555190       3298790    4853980   4/10/2018         0
716-05    12861700       20754400   7892750   4/11/2018       -6119400
716-06    -8717010       1585470    10302500  4/11/2018       -1190940
716-07    7900390        28052300   20151900  4/11/2018       1303460
716-11   -1641360        3482290    5123650   4/11/2018       -86170

我需要创建“Daily_Change”上方的列,这是每个帐户Debit_Balance的每日差异。所以帐户716-05的Debit_Balance为4/11/2018减去716-05的Debit_Balance为4/10/2018。在大约一个月的时间内,大约有30个帐户。

我目前使用的查询:

select account, balance as Debit_Balance, int_balance as "Long", 
short_mkt_value as Short, report_date as Date
from table
where group_name = "Carter"
and report_date in
(
select report_date
from table
group by report_date
order by account asc)
order by report_date asc, account asc

1 个答案:

答案 0 :(得分:1)

尝试以下

SELECT t1.*,t1.balance-t2.balance Daily_Change
FROM TestData t1
LEFT JOIN TestData t2
ON t2.report_date=DATE_SUB(t1.report_date, INTERVAL 1 DAY)
  AND t1.account=t2.account
ORDER BY t1.report_date,t1.account

SQL小提琴 - http://www.sqlfiddle.com/#!9/033d7b/10