开发者

How to calculate the running difference of the same column in a table with SQL query?

开发者 https://www.devze.com 2023-03-10 21:53 出处:网络
I have the following table structure with data as ReadingDateUnit 01-05-201110 01-06-201120 01-07-201140

I have the following table structure with data as

ReadingDate   Unit
01-05-2011    10 
01-06-2011    20 
01-07-2011    40 
01-08-2011    40  

AND I want to the following result 开发者_高级运维with T-Sql query. I am using sql server 2008 R2

  ReadingDate   Unit   UnitConsumed 
    01-05-2011    10      10
    01-06-2011    20      10
    01-07-2011    40      20
    01-08-2011    40      0


This can be done in SQL Server using the LAG function. See LAG function.


You could try the following:

With tblDifference as
(
    Select Row_Number() OVER (Order by ReadingDate) as RowNumber,ReadingDate,Unit from  TestTable
)

Select Cur.ReadingDate, Cur.Unit, ISNULL((Cur.Unit-Prv.Unit),Cur.Unit) as UnitConsumed
from tblDifference Cur 
Left Outer Join tblDifference Prv 
On Cur.RowNumber=Prv.RowNumber+1

Plain and simple !

0

精彩评论

暂无评论...
验证码 换一张
取 消