SQL技巧:创建用来按小时报告的查询

SQL技巧:创建用来按小时报告的查询,第1张

SQL技巧:创建用来按小时报告的查询,第2张

要创建每小时报告一次的查询,首先创建一个表。表格的一列记录了日期,但没有时间信息;另一栏记录小时数。下表中有一列记录了不同的处理类型。例如,我们可以按小时找到处理类型的总数。
create table test
(start time datetime not null
default current_timestamp,
start date datetime not null
default convert(datetime,convert(char(10),current_timestamp,110)),
start hour int not null
default datepart(hh,current _ timestamp),
trantype int not null
constraint CK _ trantype check(trantype in
(
中的trantype

插入测试(starttime,trantype)值(current_timestamp,3)
插入测试(starttime,trantype)值(current_timestamp,2)
插入测试(starttime,trantype)值(current_timestamp,3)
go

declare @ HR int
set @ HR = datepart(hh,dateadd(hh,-1,current_timestamp))

insert test (starttime,trantype,start hour)_
values(dateadd(hh,-1,current_timestamp),3,@hr)
insert test (starttime,trantype,start hour)_
values(dateadd(hh,-1,current_timestamp),1,@hr)
insert test (starttime,trantype,start hour)_
values(dateadd(hh,-1,current_timestamp),2,@hr)
go

然后使用查询来查找每天和每小时的处理总数。

select startdate tran_day,
starthour tran_hour
,case trantype当1时然后' insert '
当2时然后' update '
当3时然后' delete '
else ' unknown '
end transtype,
count(*)tran _ total
from
test
group by
start date,
starthour
,trans

drop table test
go

位律师回复
DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
白度搜_经验知识百科全书 » SQL技巧:创建用来按小时报告的查询

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情