如何使用下一个日期列的值来计算当前列的增量

时间:2018-09-03 09:44:54

标签: sql mysqli

我有一个临时表

BusinessDate    SSQ_CompScore
2011-01-05 00:00:00.000 41
2011-01-06 00:00:00.000 6
2011-01-07 00:00:00.000 1
2011-01-10 00:00:00.000 8
2011-01-11 00:00:00.000 48
2011-01-12 00:00:00.000 50
2011-01-13 00:00:00.000 59

我需要计算每个当前日期的增量。 我已经准备好了一个解决方案,但由于日期不连续,所以它不起作用。 你能帮忙吗?

select t1.businessdate, t1.ssq_compscore, (t2.ssq_compscore - t1.ssq_compscore) as delta
from #temp t1
left join #temp t2 on  t1.businessdate = DATEADD(dd,1,t2.businessdate)
where t1.businessdate >='20180814' 

结果集应为

BusinessDate            SSQ_CompScore Delta
2011-01-05 00:00:00.000   41           NULL
2011-01-06 00:00:00.000   6            35 
2011-01-07 00:00:00.000   1            5
2011-01-10 00:00:00.000   8            7
2011-01-11 00:00:00.000   48          40 
2011-01-12 00:00:00.000   50           2
2011-01-13 00:00:00.000   59           9

1 个答案:

答案 0 :(得分:0)

不确定这是否是最有效的方法,但据我所知

SELECT businessdate, SSQ_CompScore , 
       SSQ_CompScore - (SELECT SSQ_CompScore 
                        FROM temp 
                        WHERE businessdate < t1.businessdate
                        ORDER BY businessdate DESC
                        LIMIT 1) as delta
FROM temp t1
ORDER BY businessdate ASC