Get Last Two Rows Value Difference (T-sql )


SQL Server 2012 or 2014 solution.


 CREATE TABLE MeterReading
(
 ReadingID int,
 MeterID int,
 DataCounter int,
 Value numeric(16,4)
)
INSERT INTO MeterReading 
VALUES(1, 1, 1, 102.45)
INSERT INTO MeterReading 
VALUES(2, 2, 1, 110.45)
INSERT INTO MeterReading 
VALUES(3, 1, 2, 110.58)
INSERT INTO MeterReading 
VALUES(4, 2, 2, 115.89)
INSERT INTO MeterReading 
VALUES(5, 1, 4, 120.00)
INSERT INTO MeterReading 
VALUES(6, 2, 4, 106.23)
--Here i need the difference of latest (based on DataCounter) difference of Values corresponding MeterID


;with mycte as (
select  * , abs(value-avg(value) Over(Partition by MeterID Order by DataCounter desc ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING ))*2 as LastTwoDiffVal 
,row_number() Over(Partition by MeterID Order by DataCounter desc) rn from MeterReading ) 
Select ReadingID,
 MeterID,
 DataCounter, Value, LastTwoDiffVal from mycte
WHERE rn=1
Order by MeterID
--Or;with mycte as (
select  * , max(value) Over(Partition by MeterID Order by DataCounter desc ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING ) -  min(value) Over(Partition by MeterID Order by DataCounter desc ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING ) as LastTwoDiffVal  
,row_number() Over(Partition by MeterID Order by DataCounter desc) rn from MeterReading ) 
Select ReadingID, MeterID, DataCounter, Value, LastTwoDiffVal  from mycte
WHERE rn=1
Order by MeterID


drop table MeterReading


 

http://social.msdn.microsoft.com/Forums/en-US/ca938faf-49a7-4212-afd2-19046cbfcc8b/diffrence-of-last-2-rows?forum=transactsql

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s