sql - 查找最后两行的天差
问题描述
我要做的是找到 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
解决方案
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;
推荐阅读
- java - 了解 ssl 文件和机制
- sql-server - SQL Server 存储过程在从另一个服务器/框架调用时不执行命令,但在本地工作
- python - 我正在尝试将 Dlibs 中面部特征的坐标转换为标准(X,Y)坐标
- swift - 我们怎样才能把所有照片从画廊到收藏视图?我有这个,但它不起作用
- flutter - 在颤动的卡片堆栈视图中将前面的卡片动画到后面
- sharepoint - Can i get the contents of historized sharepoint file with the logic app connector Get file Content (Sharepoint)?
- python - 将具有 3 列通用标题的数据框列表导出到 Excel
- reactjs - 如何在 React 中的动态元素列表上访问 focus()?多次使用Ref
- linux - 如果找不到文件,则将 linux `find` 和 `cp` 与输出结合起来
- product - 如何使用顶/底线和插入符号来设置 Squarespace 产品下拉/选择元素的样式?