我想在一天内将时间间隔提取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
我怎么能得到这个?
答案 0 :(得分: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
答案 1 :(得分: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)