sql查询 - 同一列的行值之间的差异

时间:2015-02-12 07:18:47

标签: sql ms-access

有人能告诉我如何计算同一列的行之间的差异吗?

ID   DeviceID      Reading       Date         Flag
1       2           10          12/02/2015      1
2       3           08          12/02/2015      1
3       2           12          12/02/2015      1
4       2           20          12/02/2015      0
5       4           10          12/02/2015      0
6       2           19          12/02/2015      0

在ABOVE表格中,我想计算某些日期(例如12/02/2015)的DeviceID 2读数之间的差异,例如,     (12-10 = 2)     (20-12 = 8)     (19-2 = -1)并想总结这种差异 即2 + 8 +( - 1)= 9

2 个答案:

答案 0 :(得分:0)

如果您使用MS Access,我会尝试使用此代码来解决您的问题: 我在MS Access中进行了4次查询: Query1获取数据deviceId = 2和date = 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

然后是最终查询以从query3中的结果差异中获得总和:

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

答案 1 :(得分:0)

您可以尝试此操作(将Table1替换为您的表名):

SELECT  Sum([Diffs].[Difference]) AS FinalReading
FROM (
        SELECT IDs.DeviceID, [Table1].Reading AS NextReading, Table1_1.Reading AS PrevReading, [Table1].Reading-Table1_1.Reading AS Difference
        FROM (
                (
                    SELECT      [Table1].DeviceID,
                                [Table1].ID,
                                CLng(Nz(DMax("ID","Table1","[DeviceID] = " & [DeviceID] & " And [ID] < " & [ID]),0)) AS PrevID
                    FROM        Table1
                    WHERE       DeviceID = 2
                )  AS IDs
                INNER JOIN Table1
                ON IDs.ID=[Table1].ID)
                INNER JOIN Table1 AS Table1_1
                ON IDs.PrevID=Table1_1.ID
            )  AS Diffs;

ID表表达式计算相关DeviceID的prev ID。 (我把WHERE子句放在这个表的表达式中,但如果你想一次为所有设备计算FinalReadings,你可以把它移到外面的那个,最后过滤它。效率更低但更灵活。)我们加入了从内表表达式的ID和PrevIDs上的原始表,获取其读取值,并在Diffs表表达式中执行差异操作。最后的外部查询只是对每行值的差值进行求和。