0

我需要帮助来创建查询。我的问题是我有一个 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
4

3 回答 3

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)从日期中删除小时和分钟。它通过计算自 date 以来的小时数0,然后添加该小时数来做到这一点0

SQL Fiddle 上的实时示例。

于 2012-11-21T15:46:34.313 回答
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
于 2012-11-21T15:36:31.587 回答
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)) 
于 2012-11-21T15:38:15.357 回答