Home >Backend Development >PHP Tutorial >SQL Tip: Create a Query to Report by Hour_PHP Tutorial
To create a query that can report hourly, first create a table. One column of this table records the date without time information; the other column records the hour. The table below has a column recording the 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 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 processes 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 BY
StartDate,
StartHour
,trantype
ORDER BY StartDate, StartHour
COMPUTE SUM(COUNT(*)) BY StartDate, StartHour
GO
Removing test can clear the test table.
DROP TABLE test
GO