本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。要创建一个可以每个小时报告的查询,首先要创建一个表格。该表格一列记录日期,而没有时间信息;另一列记录钟点。下面的表格有一列记录了不同的处理类型。例如,我们可以按小时找出处理类型的总数。
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
接下来,插入test的数据来模拟一个可能的样本。
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
然后用一个查询来找出按日和小时的处理总数。
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
去掉test可以清空test表格。
drop table test
go