Home > Backend Development > PHP Tutorial > SQL Tip: Create a Query to Report by Hour_PHP Tutorial

SQL Tip: Create a Query to Report by Hour_PHP Tutorial

WBOY
Release: 2016-07-13 17:01:46
Original
970 people have browsed it

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631138.htmlTechArticleTo 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...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template