要創建一個可以每個小時報告的查詢,首先要創建一個表格。該表格一列記錄日期,而沒有時間信息;另一列記錄鐘點。下面的表格有一列記錄了不同的處理類型。例如,我們可以按小時找出處理類型的總數。
CREATE TABLE test
(StartTime DATETIME NOT NULL
DEFAULT CURRENT_TIMESTAMP,
StartDate DATETIME NOT NULL
DEFAULT CONVERT(DATETIME, CONVERT(CHAR(10),CURRENT_TIMESTAMP, 110)),
StartHour INT NOT NULL
DEFAULT DATEPART(hh,CURRENT_TIMESTAMP),
TranType INT NOT NULL
CONSTRAINT ck_TranType CHECK ( TranType IN
(
1, -- insert
2, -- update
3, -- delete
)
DEFAULT 1
)
GO
接下來,插入test的數據來模擬一個可能的樣本。
INSERT test (StartTime, TranType) VALUES (CURRENT_TIMESTAMP, 3)
INSERT test (StartTime, TranType) VALUES (CURRENT_TIMESTAMP, 2)
INSERT test (StartTime, TranType) VALUES (CURRENT_TIMESTAMP, 3)
GO
DECLARE @hr int
SET @hr = DATEPART(hh, DATEADD(hh,-1,CURRENT_TIMESTAMP) )
INSERT test (StartTime, TranType, StartHour) _
VALUES (DATEADD(hh,-1,CURRENT_TIMESTAMP), 3, @hr)
INSERT test (StartTime, TranType, StartHour) _
VALUES (DATEADD(hh,-1,CURRENT_TIMESTAMP), 1, @hr)
INSERT test (StartTime, TranType, StartHour) _
VALUES (DATEADD(hh,-1,CURRENT_TIMESTAMP), 2, @hr)
GO
然後用一個查詢來找出按日和小時的處理總數。
SELECT StartDate tran_day,
StartHour tran_hour
, CASE trantype WHEN 1 THEN 'insert'
WHEN 2 THEN 'update'
WHEN 3 THEN 'delete'
ELSE 'unknown'
END trantype,
COUNT(*) tran_total
FROM
Test
GROUP BY
StartDate,
StartHour
,trantype
ORDER BY StartDate, StartHour
COMPUTE SUM(COUNT(*)) BY StartDate, StartHour
GO
去掉test可以清空test表格。
DROP TABLE test
GO