原問題以下:html
Insus.NET的問題解決,分2步,1,建立一個輔助表,2,合併數據。ide
程式碼搜尋出來如圖:post
IF OBJECT_ID(N'TEMPDB.DBO.#search_data') IS NOT NULL DROP TABLE #search_data GO CREATE TABLE #search_data ([times] DATETIME,[val] INT) INSERT INTO #search_data ([times],[val]) VALUES ('2001-01-01 00:00:00',13), ('2001-01-01 00:10:00',22), ('2001-01-01 00:20:00',31), ('2001-01-01 00:40:00',5 ), ('2001-01-01 00:50:00',64), ('2001-01-01 02:30:00',73), ('2001-01-01 04:10:00',63), ('2001-01-01 04:50:00',12), ('2001-01-01 06:30:00',32)
接下來,咱們能夠建立一張輔助表:url
DECLARE @start_datetime DATETIME = '2000-01-01 00:00:00', @end_datetime DATETIME = '2000-02-01 00:00:00' ;WITH DTs([times]) AS ( SELECT @start_datetime UNION ALL SELECT [times] = DATEADD(MINUTE,10, [times]) FROM [DTs] WHERE [times] < @end_datetime ) SELECT [times] FROM [DTs] OPTION (MaxRecursion 0)
總共產生4465行記錄。spa
更多相關輔助表,能夠參考《使用CTE生成輔助表(數字或時間)等》http://www.javashuo.com/article/p-pycytexv-ep.html 和《快速生成基數的輔助表》http://www.javashuo.com/article/p-pycytexv-ep.html3d
爲了更好操做,把輔助表的產生數據存入一張臨時表中:code
IF OBJECT_ID(N'TEMPDB.DBO.#base') IS NOT NULL DROP TABLE #base GO CREATE TABLE #base ([times] DATETIME) DECLARE @start_datetime DATETIME = '2000-01-01 00:00:00', @end_datetime DATETIME = '2000-02-01 00:00:00' ;WITH DTs([times]) AS ( SELECT @start_datetime UNION ALL SELECT [times] = DATEADD(MINUTE,10, [times]) FROM [DTs] WHERE [times] < @end_datetime ) INSERT INTO #base ([times]) SELECT [times] FROM [DTs] OPTION (MaxRecursion 0)
第2步,合併數據,把程序搜索結果與輔助表的數據進行合併merge:htm
MERGE #search_data AS Target USING (SELECT [times] FROM #base) AS Source ON (Target.[times] = Source.[times]) WHEN NOT MATCHED BY TARGET THEN INSERT ([times],[val]) VALUES ([times],0); SELECT [times],[val] FROM #search_data
OK,實現方法僅供參考,完整代碼:blog
IF OBJECT_ID(N'TEMPDB.DBO.#search_data') IS NOT NULL DROP TABLE #search_data GO CREATE TABLE #search_data ([times] DATETIME,[val] INT) INSERT INTO #search_data ([times],[val]) VALUES ('2001-01-01 00:00:00',13), ('2001-01-01 00:10:00',22), ('2001-01-01 00:20:00',31), ('2001-01-01 00:40:00',5 ), ('2001-01-01 00:50:00',64), ('2001-01-01 02:30:00',73), ('2001-01-01 04:10:00',63), ('2001-01-01 04:50:00',12), ('2001-01-01 06:30:00',32) IF OBJECT_ID(N'TEMPDB.DBO.#base') IS NOT NULL DROP TABLE #base GO CREATE TABLE #base ([times] DATETIME) DECLARE @start_datetime DATETIME = '2000-01-01 00:00:00', @end_datetime DATETIME = '2000-02-01 00:00:00' ;WITH DTs([times]) AS ( SELECT @start_datetime UNION ALL SELECT [times] = DATEADD(MINUTE,10, [times]) FROM [DTs] WHERE [times] < @end_datetime ) INSERT INTO #base ([times]) SELECT [times] FROM [DTs] OPTION (MaxRecursion 0) MERGE #search_data AS Target USING (SELECT [times] FROM #base) AS Source ON (Target.[times] = Source.[times]) WHEN NOT MATCHED BY TARGET THEN INSERT ([times],[val]) VALUES ([times],0); SELECT [times],[val] FROM #search_data