如果您使用的MS Access,我試試這個代碼,你的問題: 我在MS Access中做了4個查詢: Query1獲取數據deviceId = 2和日期= 12/2/2015:
select id, reading from table1 where deviceid=2 and date=#12/2/2015#;
然後我讓QUERY2從QUERY1得到行號:
select
(select count(*) from query1 where a.id>=id) as rowno,
a.reading from query1 a;
然後我讓QUERY3得到差值場從QUERY2閱讀:
select
(tbl2.reading-tbl1.reading) as diff
from query2 tbl1
left join query2 tbl2 on tbl1.rowno=tbl2.rowno-1
然後最終查詢從中獲取總和結果區別在查詢3:
SELECT sum(diff) as Total_Diff
FROM Query3;
但是,如果您使用SQL Server,則可以使用此查詢(查找示例sqlfiddle):
;with tbl as(
select row_number()over(order by id) as rowno,
reading
from table1
where deviceid=2 and date='20150212'
)
select sum(diff) as sum_diff
from (
select
(b.reading-a.reading) as diff
from tbl a
left join tbl b on a.rowno=b.rowno-1
) tbl_diff
您正在使用哪個DBMS? – 2015-02-12 07:22:29
兩個澄清問題:1.你可以添加你想要得到的輸出嗎? 2.您使用的是什麼RDBMS? – Mureinik 2015-02-12 07:24:20
添加一些所需的輸出..你在這裏想要什麼? – 2015-02-12 07:24:50