0

我有一个名为 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 个间隔。

有没有其他方法可以做到这一点?

4

2 回答 2

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
于 2012-05-07T15:23:49.247 回答
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 只是为了简化。

于 2012-05-07T15:24:26.813 回答