您的位置:首页 > 其它

通过开始时间和结束时间按月统计工作天数

2009-10-19 19:12 691 查看
这个问题如果给出的开始时间和结束时间是不跨月的比较容易做,直接用datediff()函数求出每个时间段的天数,然后sum一下就可以了,但如果时间段跨月了,就不能这样算了。

这里借助一下master库的spt_values表,对,还是它,也可以通过自增列和其他一些系统表做个临时序列表。


--要统计每台机每个月使用情况
if object_id('[T]') is not null drop table [T]
go
create table [T]([机器号] varchar(2),[startdate] datetime,[enddate] datetime)
insert [T]
select '1#','2009-10-20','2009-10-25' union all
select '1#','2009-09-26','2009-10-05' union all
select '2#','2009-09-12','2009-09-20' union all
select '2#','2009-09-25','2009-10-10' union all
select '2#','2009-10-25','2009-11-15' union all
select '3#','2009-08-10','2009-11-05' union all
select '2#','2009-11-25','2009-12-30'

select
机器号,
convert(varchar(7),dt,120) as [年/月],
count(1) as 天数
from
(
select 机器号,dateadd(dd,b.number,a.startdate) as dt
from T as a,master..spt_values b
where b.type='P'
and dateadd(dd,b.number,a.startdate)<=a.enddate
) t
group by
机器号,convert(varchar(7),dt,120)
order by
机器号,convert(varchar(7),dt,120)

/**
机器号 年/月 天数
---- ------- -----------
1# 2009-09 5
1# 2009-10 11
2# 2009-09 15
2# 2009-10 17
2# 2009-11 21
2# 2009-12 30
3# 2009-08 22
3# 2009-09 30
3# 2009-10 31
3# 2009-11 5

(10 行受影响)
**/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐