简单的SQL查询,连接相同的表,并从一个字段中的2行获取值

时间:2017-05-20 19:02:23

标签: sql sql-server

我有一些数据

Sample table data

我需要这样的查询结果:

Result set

使用此查询:

select 
    early.sensor,
    early.event,
    late.value - early.value as value
from data_table as early 
inner join data_table as late on 
    early.sensor=late.sensor and early.event=late.event
where late.event_date > early.event_date;

我得到了这个结果:

image

1 个答案:

答案 0 :(得分:0)

假设输入表被调用" data_table"并且其中的第四列称为event_date,那么类似的东西应该这样做:

select
    early.sensor,
    early.event,
    late.value - early.value as value
from
    data_table as early
    inner join data_table as late on 
        early.sensor=late.sensor
        and early.event=late.event
where
    late.event_date > early.event_date;

但如果有两个以上的值(如@Thorston Kettner所问),那么你需要一些更复杂的逻辑。