通过一行中的查询结果获取日期时间差异组

时间:2016-01-22 12:37:41

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

我有一个结构为

的表Master_History
Id_History  Created_Date                Subscription_Type   rn
21              1/22/2016 16:31:29             1            1
22              1/22/2016 16:33:11             2            2
23              1/22/2016 16:33:37             1            3
24              1/22/2016 16:33:46             2            4
25              1/22/2016 16:33:53             1            5
26              1/22/2016 16:33:57             3            6
27              1/22/2016 16:34:01             2            7
28              1/22/2016 16:34:04             1            8
29              1/22/2016 16:34:08             3            9

我想计算与成功计算的相邻行的日期差异,但结果分布在多行

Standard    Plus    Premium
122         NULL    NULL
NULL          35    NULL
NULL        NULL    3

我需要

  • 结果像

    一样

    Standard Plus Premium 122 35 3

  • 对于最后一行(在此Subscription_Type中为3,日期差异也应在getdate()上计算,即每当我执行查询时,Premium列中的秒数应该每次反映

查询:

WITH CTE
AS (
    SELECT *
        ,ROW_NUMBER() OVER (
            ORDER BY Created_Date
            ) AS rn
    FROM Master_History
    WHERE Client_ID = 11072
    )


SELECT CASE 
        WHEN mc.Subscription_Type = 1
            THEN Sum(DATEDIFF(second, mc.Created_Date, mp.Created_Date))
        END AS [Standard]
    ,CASE 
        WHEN mc.Subscription_Type = 2
            THEN Sum(DATEDIFF(second, mc.Created_Date, mp.Created_Date))
        END AS Plus
    ,CASE 
        WHEN mc.Subscription_Type = 3
            THEN Sum(DATEDIFF(second, mc.Created_Date, mp.Created_Date))
        END AS Premium
FROM CTE mc
JOIN CTE mp ON mc.rn = mp.rn - 1
GROUP BY mc.Subscription_Type

1 个答案:

答案 0 :(得分:0)

试试这个

select 
count(Standard.*) Standard_,
count(Plus.*) Plus_,
count(Premium.*) Premium_
from
Master_History master_
left outer join Master_History Standard on Standard.Subscription_Type = 1
and master_.Subscription_Type = Standard.Subscription_Type
left outer join Master_History Plus on Plus.Subscription_Type = 2
and master_.Subscription_Type = Plus.Subscription_Type
left outer join Master_History Premium on Premium.Subscription_Type = 3
and master_.Subscription_Type = Plus.Subscription_Type
where 
convert(date,master_.Created_Date) < convert(date,getdate()) and
convert(date,master_.Created_Date) < convert(date,Standard.Created_Date) and
convert(date,master_.Created_Date) < convert(date,Plus.Created_Date) and
convert(date,master_.Created_Date) < convert(date,Premium.Created_Date)