用许多间隔填充 table

Populate table with many intervals

我必须用内部时间填充这些 table:

CREATE TABLE [dbo].[D_TIME_test](
    [DTMINUTES1] [datetime] NULL,
    [DTMINUTES5] [datetime] NULL,
    [DTMINUTES15] [datetime] NULL,
    [DTMINUTES30] [datetime] NULL,
    [DTMINUTES60] [datetime] NULL
) ON [PRIMARY]

所以我需要这样 table:

对于我使用的一列:

DECLARE @start DATETIME, @end DATETIME  

SET @start = '20120901';
SET @end = '20170101'; 

WHILE @start < @end
BEGIN
  INSERT INTO D_TIME_test
  VALUES (@start)

  SET @start = DATEADD(MINUTE, 1, @start)
END

如何更改此查询以填充上table?

试试这个

DECLARE @start DATETIME, @end DATETIME  

SET @start = '20151231 10:00';
SET @end = '20151231 15:00'; 

DECLARE @result_tbl TABLE(DTMINUTES1 DATETIME,
                          DTMINUTES5 DATETIME,
                          DTMINUTES15 DATETIME,
                          DTMINUTES30 DATETIME,
                          DTMINUTES60 DATETIME)

WHILE @start < @end
BEGIN
  INSERT INTO @result_tbl(DTMINUTES1, DTMINUTES5, DTMINUTES15, DTMINUTES30, DTMINUTES60)
  VALUES(@start, 
         DATEADD(mi, 
                 - DATEPART(mi, @start) % 5,
                 @start),
         DATEADD(mi, 
                 - DATEPART(mi, @start) % 15,
                 @start),
         DATEADD(mi, 
                 - DATEPART(mi, @start) % 30,
                 @start),
         DATEADD(mi, 
                 - DATEPART(mi, @start) % 60,
                 @start))

  SET @start = DATEADD(MINUTE, 1, @start)
END

SELECT * FROM @result_tbl

您可以先执行脚本,然后用

更新另一列
UPDATE D_TIME_test SET
  DTMINUTES5 = DATEADD(mi, (DATEDIFF(mi, 0, DTMINUTES1) / 5) * 5, 0)
, DTMINUTES15 = DATEADD(mi, (DATEDIFF(mi, 0, DTMINUTES1) / 15) * 15, 0)
, DTMINUTES30 = DATEADD(mi, (DATEDIFF(mi, 0, DTMINUTES1) / 30) * 30, 0)
, DTMINUTES60 = DATEADD(mi, (DATEDIFF(mi, 0, DTMINUTES1) / 60) * 60, 0)

或者您可以编辑脚本添加其他列

DECLARE @start DATETIME, @end DATETIME  

SET @start = '20120901';
SET @end = '20170101'; 

WHILE @start < @end
BEGIN
  INSERT INTO D_TIME_test
  VALUES (@start
        , DATEADD(mi, (DATEDIFF(mi, 0, @start) / 5) * 5, 0)
        , DATEADD(mi, (DATEDIFF(mi, 0, @start) / 15) * 15, 0)
        , DATEADD(mi, (DATEDIFF(mi, 0, @start) / 30) * 30, 0)
        , DATEADD(mi, (DATEDIFF(mi, 0, @start) / 60) * 60, 0)
         )

  SET @start = DATEADD(MINUTE, 1, @start)
END

DATEADD(mi, (DATEDIFF(mi, 0, @start) / 60) * 60, 0) 取固定值(在本例中为 0)与 @start 之间的分钟差值,并在去除除以 60 的余数后将其加回相同的值

在SQL服务器中,如果除法的两部分都是整数类型,结果也是整数类型,所以不需要使用FLOOR