状态更改之间的天数

时间:2013-01-29 22:04:11

标签: sql sql-server sql-server-2008 tsql

我有以下解决方案,但我现在需要更新它以使其有所不同。这是我现在的代码:

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

1 个答案:

答案 0 :(得分: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