要创建一个可以每个小时报告的查询,首先要创建一个表格。该表格一列记录日期,而没有时间信息;另一列记录钟点。下面的表格有一列记录了不同的处理类型。例如,我们可以按小时找出处理类型的总数。 create table test(starttime datetime not nulldefault current_timestamp,startdate datetime not nulldefault convert(datetime, convert(char(10),current_timestamp, 110)),starthour int not nulldefault datepart(hh,current_timestamp),trantype int not nullconstraint ck_trantype check ( trantype in( 1, -- insert2, -- update3, -- delete)default 1)go 接下来,插入test的数据来模拟一个可能的样本。 insert test (starttime, trantype) values (current_timestamp,)insert test (starttime, trantype) values (current_timestamp,)insert test (starttime, trantype) values (current_timestamp,)godeclare @hr intset @hr = datepart(hh, dateadd(hh,-1,current_timestamp) )insert test (starttime, trantype, starthour) _ values (dateadd(hh,-1,current_timestamp),, @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),, @hr)go 然后用一个查询来找出按日和小时的处理总数。 select startdate tran_day,starthour tran_hour, case trantype when 1 then 'insert'when then 'update'when then 'delete'else 'unknown'end trantype,count(*) tran_totalfromtestgroup bystartdate,starthour,trantypeorder by startdate, starthourcompute sum(count(*)) by startdate, starthourgo 去掉test可以清空test表格。 drop table test go
|