SQL tip: Create an hourly report query. To create a query that can be reported every hour, you must first create a table. In this table, one column records the date without the time information, and the other column records the minute. The following table contains a column to create a query that can report every hour. First, you must create a table. In this table, one column records the date without the time information, and the other column records the minute. The following table records different processing types. For example, we can find the total number of processing types by hour.
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
Next, insert the test data to simulate a possible sample.
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
Then, use a query to find the total number of processing times by day and hour.
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
StartDate,
StartHour
, Trantype
Order by StartDate, StartHour
Compute sum (COUNT (*) BY StartDate, StartHour
GO
Remove test to clear the test table.
Drop table test
GO
Bytes. In this table, one column records the date without the time information, and the other column records the minute. The following table contains a column...