使用SQL Server 2012.每天晚上,數據倉庫負載會填充貸款經歷的里程碑日期表。數據如下所示:從一系列日期開始的持續時間 - sql-server
CREATE TABLE TestData (LoanKey int, MilestoneCompletedDate datetime, Duration int)
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (2, '2013-10-16 16:51:56.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (2, '2013-10-18 15:11:29.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (2, '2013-10-23 16:21:59.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (2, '2013-10-28 14:52:00.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (2, '2013-08-26 10:53:37.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (2, '2013-09-19 15:16:38.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (2, '2013-09-20 08:31:38.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (2, '2013-10-08 15:56:05.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (2, '2013-10-16 16:11:10.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (2, '2013-10-09 11:20:35.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (2, '2013-09-10 11:15:09.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (42, '2013-06-03 16:22:32.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (42, '2013-06-21 14:46:24.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (42, '2013-08-30 10:03:08.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (42, '2013-08-30 13:55:17.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (42, '2013-09-03 15:28:22.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (42, '2013-09-04 09:30:08.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (42, '2013-09-12 10:44:46.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (42, '2013-09-25 16:06:43.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (42, '2013-06-24 11:59:25.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (42, '2013-09-25 16:06:43.000')
INSERT TestData (LoanKey, MilestoneCompletedDate) VALUES (42, '2013-01-17 15:06:14.000')
數據加載後,我想更新「持續時間」字段。下面是一些僞代碼:
UPDATE TestData SET Duration = 'Find the DateDiff between the current rows MilestoneCompletedDate and the next greatest milestone completion date for the same loan'
我可以生成與PARTITION BY和ORDER BY行號:
SELECT
LoanKey,
MilestoneCompletedDate,
ROW_NUMBER() OVER (PARTITION BY LoanKey ORDER BY MilestoneCompletedDate DESC) AS SequenceNumber
FROM
[dbo].[TestData]
在哪裏何去何從填充時段的任何想法?
謝謝你看!
Gah的問題有一個簡單的解決方案,很好的答案,我完全沒有注意2008年後的功能,「LEAD」是一個很棒的功能。 – OGHaza
謝謝你的迴應! LEAD方法存在一個問題。由LoanKey = 2和MilestoneCompletedDate = 2013-10-28定義的行的持續時間爲NULL。這是貸款的最後一個里程碑。上一個里程碑是2013-10-23,因此持續時間應該是5.看起來正確的持續時間都向下移動了一個里程碑。第二種方法將Duration添加到Ordered表中,並在DATEDIFF中反轉02和01。 – jjm
@jjm - 那是因爲你談到了一排排,然後找到下一個最好的排,所以我認爲你想根據下一個日期更新當前排。但從你的評論中,你想要的(對於任何特定的行)是找到* previous *行。在這種情況下,或者將'LAG'換成'LEAD'或者(邏輯上相同)將'ORDER BY'改爲'ASC'而不是'DESC'。 –