2016-01-22 44 views
0

我有一个表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 

回答

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) 
相关问题