使用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'。 –