显示时间间隔

时间:2012-05-07 14:53:17

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

我有一个名为Time_Summary的表,数据类似于:

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 个答案:

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

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

请注意,我使用cte只是为了简化。