我有以下代碼SQL獲取行值之間的差異?
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
,並導致
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
我想那個叫 「的OldValue」 的附加列。 OldValue Column顯示前一天的值如下(上例中爲最後三行)
33,276
7805,934
639,862
null
null
null
如何才能做到這一點?可能有一個類似的例子來展示我的方式。
在此先感謝...
UPDATE
其實,我寫了這樣的事情
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
但我不知道,這是最好的辦法嗎?
更新了我的問題。 –
是否正確使用MAX(MRD.Value)?通常它不涉及'MR.Adate'。 – Serg
代碼正常工作。 –