如何缩短截止时间

时间:2012-07-19 04:47:38

标签: sql sql-server sql-server-2000

使用SQL Server 2000

我希望将时间缩短为01:00:0001:30:0002:00:0002:30:0003:00:00

TABLE1

ID TIME

001 02:15:00 'Format (HH:mm:ss)
002 02:17:00
003 02:47:00
004 03:00:00
005 02:00:00
....

Time列的数据类型为nvarchar

条件

02:00:00 to 02:15:00 - I want to show 02:00:00 only
02:16:00 to 02:44:00 - I want to show 02:30:00 only
02:45:00 to 03:00:00 - I want to show 03:00:00 only
...

table1的预期输出

ID TIME

001 02:00:00 'Less than or equal to 2.15 mins so it should change to 02 hrs
002 02:30:00 'Less than 2.44 mins so it should change to 2.30 mins
003 03:00:00 'Greather than 2.45 mins so it should change to 03 hrs
004 03:00:00 'Same
005 02:00:00 'Same
....

如何查询此条件

需要查询帮助

4 个答案:

答案 0 :(得分:1)

试试这个:

CREATE TABLE #time(ID int, TIME nvarchar(25))

INSERT INTO #time
VALUES(001,'02:15:00'),
(002,'02:17:00'),
(003,'02:47:00'),
(004,'03:00:00'),
(005,'02:00:00')

SELECT time,CASE  
             WHEN CAST(SUBSTRING(time,CHARINDEX(':',time,1)+1,2) as int) <= 15 then LEFT(time,2)+':00:00'
             WHEN CAST(SUBSTRING(time,CHARINDEX(':',time,1)+1,2) as int) >15 and CAST(SUBSTRING(time,CHARINDEX(':',time,1)+1,2) as int) <=45 then LEFT(time,2)+':30:00' 
             WHEN CAST(SUBSTRING(time,CHARINDEX(':',time,1)+1,2) as int) >45 and CAST(SUBSTRING(time,CHARINDEX(':',time,1)+1,2) as int) <=59 then '0'+cast((cast(LEFT(time,2) as int)+1) as varchar(3))+':00:00' 
             END
FROM #time

答案 1 :(得分:0)

使用以下

CREATE FUNCTION [dbo].[RoundTime] (@Time VARCHAR(8), @RoundTo float)
RETURNS VARCHAR(8)
AS
BEGIN
   DECLARE @RoundedTime smalldatetime
   DECLARE @Multiplier float

   SET @Multiplier= 24.0/@RoundTo

   SET @RoundedTime= ROUND(CAST(CAST(CONVERT(varchar,@Time,121) AS datetime) AS float) * @Multiplier,0)/@Multiplier

   RETURN CONVERT(VARCHAR(8),@RoundedTime,108)
END



--select dbo.roundtime('02:47:00',0.5)

在一个声明中

select CONVERT(VARCHAR(8),dateadd(mi, (datediff(mi,0,'02:47:00')+29)/30*30, 0),108)

答案 2 :(得分:0)

convert(char(8), dateadd(minute, ((14+datediff(minute, 0, cast(Time as datetime)))/30)*30, 0), 108) as Time

SE-Data

答案 3 :(得分:0)

也试试这个

select 
    id,
    time,
    convert(varchar(10),dateadd(minute,datediff
        (
        minute,
        case when hours<=15 then -15 when hours>15 then 15  else 0 end,
        time)/30*30,0) ,108)
    as cut_off_time
from
(
    select id,time,
        datepart(minute,cast(time as datetime)) as hours from #time
) as t