这是原始数据表:
DeviceNo Datetime Data
12345 2015-08-01 01:25:51.120 520
12345 2015-08-01 01:25:52.320 521
12345 2015-08-01 01:25:53.510 526
12345 2015-08-01 01:25:54.420 528
12345 2015-08-01 01:25:55.380 539
12345 2015-08-01 01:26:01.860 560
12345 2015-08-01 01:26:02.310 561
12345 2015-08-01 01:26:05.520 562
12345 2015-08-01 01:26:06.125 565
12345 2015-08-01 01:26:07.723 569
12345 2015-08-01 01:26:08.920 591
12345 2015-08-01 01:26:09.250 596
我想编写一个sql来获得如下结果:
DeviceNo Datetime Data
12345 2015-08-01 01:25:51 520
12345 2015-08-01 01:25:52 521
12345 2015-08-01 01:25:53 526
12345 2015-08-01 01:25:54 528
12345 2015-08-01 01:25:55 539
12345 2015-08-01 01:25:56 null
12345 2015-08-01 01:25:57 null
12345 2015-08-01 01:25:58 null
12345 2015-08-01 01:25:59 null
12345 2015-08-01 01:26:00 null
12345 2015-08-01 01:26:01 560
12345 2015-08-01 01:26:02 561
12345 2015-08-01 01:26:03 null
12345 2015-08-01 01:26:04 null
12345 2015-08-01 01:26:05 562
12345 2015-08-01 01:26:06 565
12345 2015-08-01 01:26:07 569
12345 2015-08-01 01:26:08 591
12345 2015-08-01 01:26:09 596
我编写一个sql来按分钟显示数据,并在某些分钟内没有数据时显示null,如下面的结果表。 感谢。
答案 0 :(得分:0)
您需要为设备no生成每分钟的数据,然后将其与原始表连接,以获得预期结果。您可以使用递归cte。
生成数据示例:
WITH dates AS (
SELECT CAST('2015-01-01' AS DATETIME) 'date'
UNION ALL
SELECT DATEADD(MINUTE, 1, t.date)
FROM dates t
WHERE DATEADD(MINUTE, 1, t.date) < '2015-02-01')
SELECT * from dates
option (maxrecursion 0)
注意:您可能希望从原始表中剪切毫秒以加入