2012-05-07 114 views
0

我有一個名爲Time_Summary表和數據loks這樣的:顯示時間間隔

A_Date       A_Interval   Acc_name 
2012-05-06 00:00:00.000  0530     Nick 
2012-05-06 00:00:00.000  0600     Nick 
2012-05-06 00:00:00.000  0630     Nick 
2012-05-06 00:00:00.000  0700     Nick 
2012-05-06 00:00:00.000  0800     Nick 

我想作爲裏邊反輸出:

A_Date       A_Interval     Acc_name 
2012-05-06 00:00:00.000  05:30 - 05:59     Nick 
2012-05-06 00:00:00.000  06:00 - 06:29     Nick 
2012-05-06 00:00:00.000  06:30 - 06:59     Nick 
2012-05-06 00:00:00.000  07:00 - 07:29     Nick 
2012-05-06 00:00:00.000  08:00 - 08:29     Nick 

我試圖寫這樣的事:

Select A_Date, 
Case When A_Interval = '0530' then '05:30 - 05:59' End as A_Interval 
from Time_Summary 

但通過這樣做,我必須寫24個案例的陳述,因爲我每天會有24個時間間隔。

有沒有不同的方式這樣做?

回答

2

如果A_Interval總是看起來像,那麼這應該工作:

SELECT A_Date, 
     LEFT(A_Interval,2) + ':' + RIGHT(A_Interval,2) + ' - ' + LEFT(A_Interval,2) + ':' + 
     CASE WHEN RIGHT(A_Interval,2) = '30' THEN '59' ELSE '29' END A_Interval, 
     Acc_name 
FROM Time_Summary 
+0

非常感謝! – peter

1

這應該工作:

with cte as(
    select A_Date 
    ,  A_Interval 
    ,  Acc_name 
    ,  CAST(SUBSTRING(A_Interval,1,2)AS INT) AS Hour 
    ,  CAST(SUBSTRING(A_Interval,3,2)AS INT) AS Minute 
    ,  DATEADD(minute, 
       CAST(SUBSTRING(A_Interval,3,2)AS INT), 
        DATEADD(hour, 
         CAST(SUBSTRING(A_Interval,1,2)AS INT), 
         A_Date))as RealTime 
    FROM Time_Summary 
) 
SELECT A_Date 
     , RIGHT('00' + CAST(Hour AS varchar(2)),2) + ':' 
     + RIGHT('00' + CAST(Minute AS varchar(2)),2) + ' - ' 
     + RIGHT('00' + CAST(DATEPART(hh,DATEADD(mi,29,RealTime)) AS varchar(2)),2) + ':' 
     + RIGHT('00' + CAST(DATEPART(mi,DATEADD(mi,29,RealTime)) AS varchar(2)),2) AS A_Interval 
     , Acc_name 
FROM cte 

結果:

A_Date      A_Interval   Acc_name 
2012-05-06 00:00:00.000 05:30 - 05:59  Nick 
2012-05-06 00:00:00.000 06:00 - 06:29  Nick 
2012-05-06 00:00:00.000 06:30 - 06:59  Nick 
2012-05-06 00:00:00.000 07:00 - 07:29  Nick 
2012-05-06 00:00:00.000 08:00 - 08:29  Nick 

請注意,我用的只是爲了簡化。