值与第二值之间的差异

时间:2017-10-22 19:03:23

标签: sql sql-server difference

我在SQL Server 2014中有这种表:

event_type    | value      | time
  ------------+------------+--------------------
   2          | 5          | 2015-05-09 12:42:00
   4          | -42        | 2015-05-09 13:19:57
   2          | 2          | 2015-05-09 14:48:30
   2          | 7          | 2015-05-09 12:54:39
   3          | 16         | 2015-05-09 13:19:57
   3          | 20         | 2015-05-09 15:01:09

需要查询最新和第二最新值之间的差异。当然,仅适用于不止一次登记的活动。

2 个答案:

答案 0 :(得分:1)

这是你想要的吗?

select t.*, (value - prev_value) as diff
from (select t.*,
             lag(value) over (partition by event_type order by time) as prev_value
      from t
     ) t
where prev_value is not null;

编辑:

lag()通常效率更高,但您也可以使用apply

select t.*, (t.value - prev.value) as diff
from t cross apply
     (select top 1 tprev.*
      from t tprev
      where tprev.event_type = t.event_type and tprev.time < t.time
      order by tprev.time desc
     ) tprev;

答案 1 :(得分:1)

这是使用row_number

获取最新和第二最新值的方法
select event_type, sum(case when rn = 1 then value else -value end) from (
    select event_type, value, 
        row_number() over (partition by event_type order by time desc) rn
    from mytable
) t where rn <= 2
group by event_type
having count(*) = 2

如果您想要绝对差异,那么您可以使用abs(sum(...))