列是每天相同列的值之间的差异

时间:2018-04-19 10:37:59

标签: mysql sql

我的表格如下:

Balance          Value 1        Value2          Date        Daily Change (Expected)  
8                8,648,668.60   12,620,390.51   3/27/2018     -1
7                3,087,707.30   3,494,174.70    3/28/2018     -1
6                3,039,443.51   2,345,356.15    3/29/2018     -1

如何格式化查询以使“每日更改”列是后一天的余额与前者的差异?

让我的表格称为“表格”

按顺序

3/27/2018 - 3/26/2018

3/28/2018 - 3/27/2018

3/29/2018 - 3/28/2018

2 个答案:

答案 0 :(得分:2)

您可以使用left join

select t.*,
       (t.balance - tprev.balance) as daily_change
from `table` t left join
     `table` tprev
     on t.date = tprev.date  + interval 1 day;

答案 1 :(得分:0)

我使用以下内容来回答这个问题:

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