计算当前值与记录的最后一个值之间的差值

时间:2016-01-05 15:36:35

标签: sql-server sql-server-2012 difference

我想创建一个查询来计算当前值与记录的最后一个值之间的差异(以米为单位)。

关注我的SpareParts表:

 ----------------------------
|Serial | PartCode | Meter  | 
 ----------------------------
|   1   |    A     | 1000   |
|   1   |    A     | 2000   |
|   1   |    A     | 2500   |
|   1   |    A     | 4000   |
|   2   |    A     | 1000   |
|   2   |    A     | 1400   |
|   2   |    A     | 2900   |
|   1   |    B     | 5000   |
|   1   |    B     | 9000   |
|   1   |    B     | 14000  |
 ----------------------------

我希望得到这样的结果:

 -----------------------------------
|Serial | PartCode | Meter  | Diff  |
 -----------------------------------
|   1   |    A     | 1000   |  0    |   
|   1   |    A     | 2000   | 1000  |
|   1   |    A     | 2500   | 500   |
|   1   |    A     | 4000   | 1500  |
|   2   |    A     | 1000   |  0    |
|   2   |    A     | 1400   | 400   |
|   2   |    A     | 2900   | 1500  |
|   1   |    B     | 5000   |  0    |
|   1   |    B     | 9000   | 4000  |
|   1   |    B     | 14000  | 5000  |
 -----------------------------------
Diff = Current Meter - Last Meter

你能帮我解决这个问题吗?

谢谢,

1 个答案:

答案 0 :(得分:1)

这可能对您有用:

SELECT Serial, PartCode, Meter, 
   LAG(Meter, 1,0) OVER (PARTITION BY Serial, PartCode ORDER BY Meter DESC) AS Diff
FROM SpareParts;

由于您使用的是SQL Server 2012.这会将表分为由序列号和部件代码定义的行(分区)组,按仪表值对每个集合进行排序,然后计算1-back行之间的差异