我想要做的是找到 MAX 日期并在最近的日期和倒數第二個日期之間做一個 datediff 來為天數差異創建一個列。如何擺脫前兩行?我試圖通過將它包裝到另一張桌子來做 MAX,但不走運。
樣本資料:
| 專案編號 | 物品 | 最近更新時間 | 原因 |
|---|---|---|---|
| 123 | 鉛筆 | 4/1/2020 | 更正 |
| 123 | 鉛筆 | 8/1/2020 | 更正 |
| 123 | 鉛筆 | 9/3/2020 | 更正 |
| 456 | 熒光筆 | 5/1/2020 | 更正 |
| 456 | 熒光筆 | 5/10/2020 | 更正 |
| 789 | 鋼筆 | 10/1/2020 | 更正 |
| 789 | 鋼筆 | 10/1/2020 | 更正 |
預期輸出:
| 專案編號 | 物品 | 最近更新時間 | 原因 | 自上次更正以來的天數差異 |
|---|---|---|---|---|
| 123 | 鉛筆 | 9/3/2020 | 更正 | 33 |
| 456 | 熒光筆 | 5/10/2020 | 更正 | 9 |
| 789 | 鋼筆 | 10/20/2020 | 更正 | 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
uj5u.com熱心網友回復:
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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/349849.html
標籤:sql sql-server 查询语句
上一篇:轉置并加入一列SQL
