我有以下解决方案,但我现在需要对其进行更新以使其工作有所不同。这是我现在得到的代码:
DECLARE @table TABLE (Status VARCHAR(50), StartDate DATETIME)
INSERT INTO @table VALUES ('UP', '01/01/2012')
INSERT INTO @table VALUES ('UP', '04/15/2012')
INSERT INTO @table VALUES ('Down','06/12/2012')
INSERT INTO @table VALUES ('UP','10/04/2012')
SELECT
t1.Status, t1.StartDate, ISNULL(t2.StartDate,GetDate()) AS 'EndDate',
DateDiff(day,t1.startdate,ISNULL(t2.StartDate,GetDate())) as StatusDays
FROM
(SELECT Status, StartDate, ROW_NUMBER() OVER
(ORDER BY StartDate) AS 'num' FROM @table) t1
LEFT JOIN
(SELECT Status, StartDate, ROW_NUMBER() OVER
(ORDER BY StartDate) AS 'num' FROM @table) t2
ON t1.num = t2.num-1
这让我得到了结果,但前两行都是 UP。这是我现在得到的。
Status StartDate EndDate StatusDays
UP 2012-01-01 2012-04-15 105
UP 2012-04-15 2012-06-12 58
Down 2012-06-12 2012-10-04 114
UP 2012-10-04 2013-01-29 117
所以,我想看看这个总结:
Status StartDate EndDate StatusDays
UP 2012-01-01 2012-06-12 163
Down 2012-06-12 2012-10-04 114
UP 2012-10-04 2013-01-29 117