1

我想在给定的一天中将时间间隔提取 30 分钟。

例如:如果我将日期指定为 05/06/2013,那么我希望输出为:

Day                  Interval
05/06/2013           0000-0030
05/06/2013           0030-0100
05/06/2013           0100-0130
05/06/2013           0130-0200
05/06/2013           0200-0230
----------           ---------
----------           ---------
05/06/2013           2300-2330
05/06/2013           2330-0000

我怎样才能得到这个?

4

2 回答 2

0

这是一个使用内联表值函数的解决方案,您可以重复使用该函数来获取任何间隔的日期所需的任何范围。您可以通过将日期时间转换为字符串并在其上使用字符串函数来获得所需的确切输出。

--A function that returns all intervals between start and end
CREATE FUNCTION GetTimeIntervals
(   
    @intervalMinutes int
    ,@startDateTime datetime
    ,@endDateTime datetime
)
RETURNS TABLE 
AS
RETURN 
(
    WITH cSequence AS
    (
    SELECT  
        @startDateTime AS C_StartDateTime
        ,DATEADD(minute, @intervalMinutes, @startDateTime) AS C_EndDateTime

    UNION ALL
    SELECT
        C_EndDateTime AS C_StartDateTime
        ,DATEADD(minute, @intervalMinutes, C_EndDateTime) AS C_EndDateTime
    FROM cSequence 
    WHERE DATEADD(minute, @intervalMinutes, C_EndDateTime) <= @endDateTime
    )
    select C_StartDateTime, C_EndDateTime FROM cSequence
);

GO
--Example implementation
DECLARE @times TABLE (Id INT IDENTITY(1,1),time1 DATETIME,time2 DATETIME);
INSERT INTO @times VALUES ('2013-05-07 08:00','2013-05-07 10:00'),('2013-05-08','2013-05-09')
DECLARE @Interval INT = 30;

SELECT
Id
,fn.C_StartDateTime
,fn.C_EndDateTime
,REPLACE(RIGHT(CONVERT(VARCHAR(16),fn.C_StartDateTime,121),5)+'-'+RIGHT(CONVERT(VARCHAR(16),fn.C_EndDateTime,121),5),':','') AS Interval
FROM @times AS t
CROSS APPLY GetTimeIntervals(@Interval,time1,time2) AS fn
OPTION(MAXRECURSION 0)
于 2013-05-07T07:19:55.870 回答
0

来吧,我承认不是很优雅。如果您需要经常这样做,最好只创建一个表并添加 Pondlife 建议的值。

declare @date date
set @date = current_timestamp

declare @table table (dt date, interval varchar(10))
declare @interval time
set @interval = '00:00'
while @interval < '23:29'
begin
    insert into @table (dt,interval)
    select @date, 
        right('0000' + 
            substring(convert(varchar,@interval),1,2) + 
            substring(convert(varchar,@interval),4,2),4)
        + '-' + 
        right('0000' + 
            substring(convert(varchar,dateadd(minute,30,@interval)),1,2) + 
            substring(convert(varchar,dateadd(minute,30,@interval)),4,2),4)
    set @interval = dateadd(minute,30,@interval)
end

insert into @table (dt,interval)
select @date, '2330-0000'

select *
from @table
于 2013-05-06T19:10:35.197 回答