I have following code
SELECT MRT.sno, MRT.TypeName, MR.Adate, MAX(MRD.Value) AS Value
FROM MeterReadings MR
INNER JOIN MeterReadingDetails MRD ON MRD.ReadingId = MR.sno
INNER JOIN MeterReadingTypes MRT ON MRT.sno = MRD.ReadingTypeId
WHERE MRT.sno IN (7,10,11)
GROUP BY MRT.sno,MRT.TypeName,MR.Adate
ORDER BY MR.Adate DESC
And result
sno TypeName Adate Value
11 Toplam Kapasitif 2013-01-04 00:00:00 33,313
7 Toplam 2013-01-04 00:00:00 7819,33
10 Toplam Reaktif 2013-01-04 00:00:00 640,492
11 Toplam Kapasitif 2013-01-03 00:00:00 33,276
7 Toplam 2013-01-03 00:00:00 7805,934
10 Toplam Reaktif 2013-01-03 00:00:00 639,862
I want an additional column that named “OldValue”. OldValue Column shows previous day value like following (last three row for above example)
33,276
7805,934
639,862
null
null
null
How Can I do this? There may be a similar example to show me the way.
Thanks in advance…
UPDATE
In fact, I wrote something like this
SELECT MRT.sno, MRT.TypeName, MR.Adate, MAX(MRD.Value) AS Value,
(SELECT Value From
(SELECT TOP 1 XMR.Adate,XMRD.ReadingTypeId,MAX(XMRD.Value) AS Value
FROM MeterReadings XMR,MeterReadingDetails XMRD
WHERE XMRD.ReadingId = XMR.sno AND XMRD.ReadingTypeId = MRT.sno AND XMR.Adate<MR.Adate
GROUP BY XMR.Adate,XMRD.ReadingTypeId
ORDER BY XMR.Adate DESC) AS TBL
) AS OldValue
FROM MeterReadings MR
INNER JOIN MeterReadingDetails MRD ON MRD.ReadingId = MR.sno
INNER JOIN MeterReadingTypes MRT ON MRT.sno = MRD.ReadingTypeId
WHERE MRT.sno IN (7,10,11)
GROUP BY MRT.sno,MRT.TypeName,MR.Adate
But I dont know, Is this best way?
If you’r using SQL Server 2012, you could use the new
LAGanalytical functionYour statement then becomes
Using SQL Server 2005/2008, I would write the statement as
Edit
The main difference between using either one of these solutions to yours is that your solution has to retrieve the previous result for each record, an expensive operation, while this solutions in essence can join two complete (identical) sets of data.