在时间数据中创建缺失的分钟记录以完成一天(每天1440条记录)

时间:2015-09-07 20:41:39

标签: sql database sql-server-2008 tsql

我有一个数据源,出于所有意图和目的,它基于网络分析,表基数是1行=选择日期范围内每个日期的每小时的每分钟。有时,此数据不会返回当天每分钟的记录(在该分钟期间未在数据源中注册任何活动)。一个例子如下,缺少的分钟是17:26和17:28:

+------------+------+--------+--------+---------+
|    Date    | Hour | Minute | Visits | Bounces |
+------------+------+--------+--------+---------+
| 2015-09-07 |   17 |     24 |    499 |      58 |
| 2015-09-07 |   17 |     25 |     32 |       4 |
| 2015-09-07 |   17 |     27 |     12 |       1 |
| 2015-09-07 |   17 |     29 |      6 |       0 |
+------------+------+--------+--------+---------+

出于我们的目的,我们需要每天等同于它的全部会议记录,并且这些没有注册活动的记录不应该不在数据库中,而是作为记录输入,其中包含度量列null,将输出以下内容:

+------------+------+--------+--------+---------+
|    Date    | Hour | Minute | Visits | Bounces |
+------------+------+--------+--------+---------+
| 2015-09-07 |   17 |     24 |    499 |      58 |
| 2015-09-07 |   17 |     25 |     32 |       4 |
| 2015-09-07 |   17 |     26 |      0 |       0 |
| 2015-09-07 |   17 |     27 |     12 |       1 |
| 2015-09-07 |   17 |     28 |      0 |       0 |
| 2015-09-07 |   17 |     29 |      6 |       0 |
+------------+------+--------+--------+---------+

我已经考虑过利用set功能来包含它们不存在的分钟数,但这会将丢失的记录返回到字面上,只是分钟,没有日期或小时数据将被带入记录中所以我&# 39,我必须承认我很难过!

2 个答案:

答案 0 :(得分:2)

您可能需要一个分钟表。有一些程序可以自动创建一系列分钟。查看HERE的样本数天。

CREATE TABLE minute
    ([Date] datetime, [Hour] int, [Minute] int)
GO

INSERT INTO minute
    ([Date], [Hour], [Minute])
VALUES
    ('2015-09-07 00:00:00', 17, 24),
    ('2015-09-07 00:00:00', 17, 25),
    ('2015-09-07 00:00:00', 17, 26),
    ('2015-09-07 00:00:00', 17, 27),
    ('2015-09-07 00:00:00', 17, 29)

SQL FIDDLE DEMO

 SELECT m.[Date], m.[Hour], m.[Minute], 
     CASE WHEN a.[Visits] is null then 0
          ELSE a.[Visits]
     END [Visits], 
     CASE WHEN a.[Bounces] is null then 0
          ELSE a.[Bounces]
     END [Bounces]
 FROM minute m
 left join analytic a
    on m.date = a.date
    and m.hour = a.hour
    and m.minute = a.minute

答案 1 :(得分:1)

虽然可能有更好更简单的选项,但我会这样做:

  1. 创建一个包含hourminute(1440行)所有值的表格
  2. 插入缺失值
  3. 假设您有一个名为tbl_hour_minute的表,其结构如下:

    HOUR  |  MINUTE
    ------+--------
     0    |   0
     0    |   1
     ...
     0    |   59
     1    |   0
     ...
     23   |   59
    

    你可以做这样的事情来获得缺少的时间:

    select c.*
    from 
    (
    select a.date, b.hour, b.minute
    from (select distinct date from your_table) as a
         tbl_hour_minute as b
    ) as c
    left join your_table as t on c.date = t.date and c.hour = t.hour and c.minute = t.minute
    where t.hour is null and t.minute is null;
    

    然后,您可以将数据插入到表中,如果需要,可以添加所需的零。