15分钟增量查询

时间:2016-04-15 15:43:49

标签: mysql sql datetime

我有一台当前正在处理工作的服务器。实施例

JobName               avgStartTime      avgEndTime
job1                  00:31:05.5500000  00:37:35.6170000
job2                  00:35:05.5500000  00:45:35.6170000
job3                  00:54:24.0600000  01:04:22.5700000
job4                  05:07:12.9100000  06:04:59.7800000
job5                  20:48:04.6870000  21:08:20.1430000
job6                  19:40:24.6870000  19:57:48.4570000

我想创建一个查询,该列将以15分钟为增量提供一个列,另一个将在这15分钟内处理作业。 例如。

Interval   NumberOfJobs   JobName
00:00:00   0
00:15:00   0
00:30:00   2              Job1
                          Job2
00:45:00                  Job3
01:00:00                  Job3
01:15:00    

这是我的计算15分钟增量的查询。

CREATE TABLE #15MinuteIncrements(Increment DATETIME
                         , PRIMARY KEY(Increment));

DECLARE @dIncr DATETIME =
                     (SELECT CONVERT( DATETIME, CONVERT(DATE, GETDATE())));

DECLARE @dEnd DATETIME =
                    (SELECT CONVERT( DATETIME, CONVERT(DATE,
                                                     (SELECT DATEADD(day, 1, GETDATE())))));

WHILE(@dIncr < @dEnd)
    BEGIN
       INSERT INTO                    #15MinuteIncrements(Increment)
       VALUES
            (@dIncr);
       SELECT @dIncr = DATEADD(MINUTE, 15, @dIncr);
    END;
GO

1 个答案:

答案 0 :(得分:0)

认为这将使用您的#15MinuteIncrements表。它使用多个表,但您可以将其解析为子查询。

CREATE TABLE time_log_A AS
SELECT
    JobName,
    SEC_TO_TIME(FLOOR((TIME_TO_SEC(avgEndTime)+450)/900)*900) AS I
FROM
    time_log
;

CREATE TABLE time_log_B AS
SELECT
    I,
    COUNT(DISTINCT JobName) AS NumberOfJobs
FROM
    time_log_A
GROUP BY
    I
;

SELECT DISTINCT
  INC.Increment AS "Interval",
    B.NumberOfJobs,
    A.JobName
FROM
  #15MinuteIncrements INC
  LEFT JOIN time_log_A A
      ON A.I = INC.Increment
    LEFT JOIN time_log_B B
      ON A.I = INC.Increment
ORDER BY
  INC.Increment,
    A.JobName
;