我需要帮助才能创建查询。我的问题是我有一个StartDate和EndDate,需要在60分钟的集团中分开。
DECLARE @STARTDATE AS SMALLDATETIME
DECLARE @ENDDATE AS SMALLDATETIME
SET @STARTDATE = '2012-11-21 11:03:00'
SET @ENDDATE = '2012-11-21 13:04:00'
我需要回报:
Hour, Time
11 , 57
12 , 60
13 , 04
答案 0 :(得分:1)
您可以使用递归CTE。例如:
declare @startDate datetime = '2012-11-21 22:05:00'
declare @endDate datetime = '2012-11-22 01:06:00'
; with TimeList as
(
select @startDate as dt
union all
select dateadd(hour, 1, dateadd(hour, datediff(hour, 0, dt), 0))
from TimeList
where dateadd(hour, 1, dt) < @endDate
)
select dt
from TimeList
union all
select @endDate
代码段dateadd(hour, datediff(hour, 0, dt), 0)
会删除日期中的小时和分钟。它是通过计算自约会0
以来的小时数,然后再添加到目前为止的小时数0
来实现的。
答案 1 :(得分:0)
我不确定我是否理解你,但这会在你的开始日期之后每隔60分钟返回一小时和一分钟。
DECLARE @STARTDATE AS SMALLDATETIME
DECLARE @ENDDATE AS SMALLDATETIME
DECLARE @time AS TABLE(id int identity(1,1), [hour] int, [time] int)
SET @STARTDATE = '2012-11-21 11:03:00'
SET @ENDDATE = '2012-11-21 13:04:00'
WHILE @STARTDATE < @ENDDATE
BEGIN
SELECT @STARTDATE = DATEADD(MINUTE,60,@STARTDATE)
INSERT INTO @time (hour,time)
VALUES(DATEPART(HOUR,@STARTDATE),DATEPART(MINUTE,@STARTDATE))
END
SELECT * FROM @time
答案 2 :(得分:0)
你可以分三件做。第一件是第一个小时,第60件减去分钟值,第二件是时间= 60表示从开始+ 1到结束之间的所有小时,第三件是结束分钟
然后将它们插入到临时表中,就像abstractChaos所做的那样。
像AbstractChaos一样插入临时表:
DECLARE @STARTDATE AS SMALLDATETIME
DECLARE @ENDDATE AS SMALLDATETIME
DECLARE @TIME AS TABLE(id INT IDENTITY(1,1), [HOUR] INT, [TIME] INT)
SET @STARTDATE = '2012-11-21 11:03:00'
SET @ENDDATE = '2012-11-21 13:04:00'
INSERT INTO @TIME (HOUR,TIME)
VALUES (datepart(HOUR,@startdate) ,60 - datepart(MINUTE,@startdate) )
WHILE @STARTDATE < @ENDDATE
BEGIN
SELECT @STARTDATE = DATEADD(MINUTE,60,@STARTDATE)
INSERT INTO @TIME (HOUR,TIME)
VALUES(datepart(HOUR,@STARTDATE) , 60)
END
INSERT INTO @TIME (HOUR,TIME)
VALUES(datepart(HOUR,@enddate) , datepart(MINUTE,@startdate))