首页 > 解决方案 > 查找最后两行的天差

问题描述

我要做的是找到 MAX 日期并在最近日期和倒数第二个日期之间进行 datediff,以创建一个单独的列来表示天数差异。如何摆脱前两行?我试图通过将另一张桌子包装起来来做一个 MAX,但没有运气。

样本数据:

项目编号 物品 最近更新时间 原因
123 铅笔 2020 年 4 月 1 日 更正
123 铅笔 2020 年 8 月 1 日 更正
123 铅笔 2020 年 9 月 3 日 更正
456 荧光笔 2020 年 5 月 1 日 更正
456 荧光笔 2020 年 5 月 10 日 更正
789 2020 年 10 月 1 日 更正
789 2020 年 10 月 1 日 更正

预期输出:

项目编号 物品 最近更新时间 原因 自上次更正后的天数差异
123 铅笔 2020 年 9 月 3 日 更正 33
456 荧光笔 2020 年 5 月 10 日 更正 9
789 2020 年 10 月 20 日 更正 19

这是我到目前为止使用的:

SELECT 
       [Item_ID]
      ,[Item]
      ,[Last_Updated]
      ,[Reason]
      ,DATEDIFF(day,lag([Last_Updated],1) over(partition by [Item_ID] ORDER BY [Last_Updated] asc), [Last_Updated]) AS DAY_DIFF
  FROM [Table]

这给了我以下信息:

Item_ID Item    Last_Updated    Reason  DAY_DIFF
123 Pencil  2020-04-01  Correction  NULL
123 Pencil  2020-08-01  Correction  122
123 Pencil  2020-09-03  Correction  33
456 Highlighter 2020-05-01  Correction  NULL
456 Highlighter 2020-05-10  Correction  9
789 Pen 2020-10-01  Correction  NULL
789 Pen 2020-10-20  Correction  19

标签: sqlsql-servertsql

解决方案


select t.* from(
SELECT 
       [Item_ID]
      ,[Item]
      ,[Last_Updated]
      ,[Reason]
      ,datediff(day, lag([Last_Updated],1,Last_Updated)over (partition by [Item_ID] order by [Last_Updated]),[Last_Updated])  as 'Difference Between Last Correction',
row_number() over (partition by [Item_ID] order by [Last_Updated] desc) as rn
  FROM [TABLE]
)t
where rn = 1;

推荐阅读