获取一个月的上一个记录减去上一个月的上一个记录

时间:2018-07-27 17:29:16

标签: sql sql-server tsql

我的公司使用远程信息处理设备来捕获由资产驱动的英里范围内的数据。我想要得到的是任何给定月份的最后一个里程表读数-上个月的最后一个里程表读数。我认为最好使用窗函数来获取每天的最大里程表值(请参见下面的示例)。

SELECT Date_FW, Vehicle_ID2_FW, Location_Code_FW, MAX(Odometer_Fw) OVER(PARTITION BY Vehicle_ID2_FW,Date_FW) as Max_Odo
FROM GPS_Trips_FW

我遇到问题的地方是试图概念化如何按日期获取给定月份的资产的最新条目(例如,如果有6/28 / 18、6 / 29/2018的条目)和6/30/2018,我只想要6/30/2018的数据,并过滤掉除此以外的任何其他信息。此外,然后减去任何给定月份的MAX里程表-上个月的MAX里程表(请参见下面的示例)。

样本查询数据:

|Date      |Asset #|Location   |Max Odo|
|6/30/2018 |1215   |Phoenix, AZ|17500  |
|6/29/2018 |1215   |Phoenix, AZ|17250  |
|6/28/2018 |1215   |Phoenix, AZ|17000  |
|…         |…      |…          |…      | 
|5/31/2018 |1215   |Phoenix, AZ|15000  |
|…         |…      |…          |…      |
|4/30/2018 |1215   |Phoenix, AZ|12000  |

所需查询结果:

|Date      |Asset #|Location   |Odo Var|
|6/30/2018 |1215   |Phoenix, AZ|2500   |
|5/31/2018 |1215   |Phoenix, AZ|3000   |

有没有简单的方法可以做到这一点?任何见识将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:0)

;With CTE_odo
As
(
Select 
    ore.Reading_Date
    , ore.Asset
    , ore.Location
    , ore.Reading
    , Row_Number() Over (Partition By ore.Asset, EOMonth(ore.Reading_Date) Order By ore.Reading_Date Desc) As RN
From dbo.Odo_Reading As ore
)

Select 
odo.Reading_Date
, odo.Asset
, odo.Location
, odo.Reading
, Lag(odo.Reading, 1) Over (Order By odo.Reading_Date) As Previous_Reading
, odo.Reading - Lag(odo.Reading, 1) Over (Order By odo.Reading_Date) As Month_Milage
From CTE_odo As odo
Where odo.RN = 1
-- this restricts the return to the last two months
And EOMonth(odo.Reading_Date) >= DateAdd(Month, -2, GetDate())

答案 1 :(得分:0)

这与Brian的方法类似,但是它修复了一些错误:

With r As (
      select r.* 
             row_Number() over (partition By r.Asset, EOMonth(r.Reading_Date) order by r.Reading_Date Desc) as seqnum
      from dbo.Odo_Reading As ore
     )
select reading_date, asset, location, reading,
       (reading - coalesce(prev_reading, 0)) as diff
from (select r.*,
             lag(r.reading, 1) Over (partition by asset order By r.Reading_Date) as Previous_Reading
      from r
      where r.seqnum = 1
     ) r
-- this restricts the return to the last two months
where EOMonth(r.Reading_Date) >= DateAdd(Month, -2, GetDate())