2

我有以下解决方案,但我现在需要对其进行更新以使其工作有所不同。这是我现在得到的代码:

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
4

1 回答 1

2

以下 T-SQL 不是最优雅的,但它可以完成这项工作:

with mycte as 
(
    select t.Status, t.StartDate, ROW_NUMBER() over (order by t.startdate) as rn
    from @table as t
), 
mycte2 as
(
    select m.Status, m.StartDate, ROW_NUMBER() over (order by m.rn) as rn2
    from mycte as m
    where not exists
    (
        select 1
        from mycte as m2
        where m2.rn=m.rn-1 and m2.status=m.Status
    )
)

select m2.Status, m2.StartDate, cast(isnull(m3.StartDate, getdate()) as date) as EndDate, 
    datediff(day,m2.StartDate, cast(isnull(m3.StartDate, getdate()) as date)) as StatusDays
from mycte2 as m2
left outer join mycte2 as m3
    on m3.rn2=m2.rn2+1
于 2013-01-29T22:58:41.213 回答