日期:2014-05-18 浏览次数:21124 次
--> 测试数据:[test]
if object_id('[test]') is not null
drop table [test]
create table [test](
[id] int,
[name] varchar(5),
[recorddate] date,
[workhours] numeric(3,2)
)
go
insert [test]
select 1,'sa','2012-06-10',8.00 union all
select 2,'sa','2012-06-11',8.00 union all
select 3,'root','2012-06-11',9.00 union all
select 4,'root','2012-06-14',7.00 union all
select 5,'admin','2012-06-15',6.00 union all
select 6,'sa','2012-06-10',3.00
go
declare @StartTime date
set @StartTime='2012-06-10'
;with t
as(
select distinct b.name,DATEADD(DD,number,@StartTime) as [recorddate]
from master..spt_values a
cross join test b
where number between 0 and 5 and type='p'
)
select t.name,t.recorddate,sum(isnull(m.workhours,0.00)) as workhours
from t
left join test m
on t.recorddate=m.recorddate and t.name=m.name
group by t.name,t.recorddate
order by t.name,t.recorddate
/*
name recorddate workhours
----------------------------------------------
admin 2012-06-10 0.00
admin 2012-06-11 0.00
admin 2012-06-12 0.00
admin 2012-06-13 0.00
admin 2012-06-14 0.00
admin 2012-06-15 6.00
root 2012-06-10 0.00
root 2012-06-11 9.00
root 2012-06-12 0.00
root 2012-06-13 0.00
root 2012-06-14 7.00
root 2012-06-15 0.00
sa 2012-06-10 11.00
sa 2012-06-11 8.00
sa 2012-06-12 0.00
sa 2012-06-13 0.00
sa 2012-06-14 0.00
sa 2012-06-15 0.00
*/
------解决方案--------------------
--> 测试数据:[test]
if object_id('[test]') is not null
drop table [test]
create table [test](
[id] int,
[name] varchar(5),
[recorddate] date,
[workhours] numeric(3,2)
)
go
insert [test]
select 1,'sa','2012-06-10',8.00 union all
select 2,'sa','2012-06-11',8.00 union all
select 3,'root','2012-06-11',9.00 union all
select 4,'root','2012-06-14',7.00 union all
select 5,'admin','2012-06-15',6.00 union all
select 6,'sa','2012-06-10',3.00
go
declare @StartTime date
set @StartTime='2012-06-10'
declare @EndTime date
set @EndTime='2012-06-15'
;with t
as(
select
distinct b.name,
DATEADD(DD,number,@StartTime) as [recorddate]
from
master..spt_values a
cross join
test b
where
number between 0 and DATEDIFF(DD,@StartTime,@EndTime)
and type='p'
)
select
t.name,
t.recorddate,
sum(isnull(m.workhours,0.00)) as workhours
from
t
left join
test m
on
t.recorddate=m.recorddate
and t.name=m.name
group by
t.name,t.recorddate
order by
t.name,t.recorddate
/*
name recorddate workhours
------------------------------------
admin 2012-06-10 0.00
admin 2012-06-11 0.00
admin 2012-06-12 0.00
admin 2012-06-13 0.00
admin 2012-06-14 0.00
admin 2012-06-15 6.00
root 2012-06-10 0.00
root 2012-