SQL tip: Create a query for hourly reporting

Source: Internet
Author: User
Tags datetime
To create a query that can report hourly, first create a table. The table has a record date, no time information, and another record hour. The following table has one column that records different processing types. For example, we can find the total number of processing types by the hour.
CREATE TABLE Test
(StartTime DATETIME not NULL
DEFAULT Current_timestamp,
StartDate DATETIME not NULL
DEFAULT Convert (DATETIME, convert (CHAR, 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 out the total number of days and hours of processing.
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

Remove test to empty the test table.
DROP TABLE Test
Go

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.