日期:2014-05-18  浏览次数:20418 次

考勤月报表Sql 问题
现有 
表A (签到表) : Id UserId Time1 Time2 (Time1上班签到时间)(Time2下班签到时间)
表B (用户表) : Id UserId Username

怎么得到这样一个月报表

姓名 1 2 3 4 5 .....31 (数字时本月的日期)
张三 出勤 出勤 出勤
李四 出勤 缺勤 出勤


高手赐教,谢谢

------解决方案--------------------
create table ta
(
Id int,
userid int,
time1 datetime,
time2 datetime
)
create table tb
(
Id int,
userid int,
username varchar(100)
)

insert tb select 1,1,'张三'
union all 
select 2,2,'李四'
insert ta select 1,1,'2007-10-1 09:00:00.000','2007-10-1 18:00:00.000'
union all 
select 2,1,'2007-10-2 09:00:00.000','2007-10-2 18:00:00.000'
union all 
select 3,1,'2007-10-3 09:00:00.000','2007-10-3 18:00:00.000'
union all 
select 4,2,'2007-10-1 09:00:00.000','2007-10-1 18:00:00.000'
union all 
select 5,2,'2007-10-2 09:00:00.000','2007-10-2 18:00:00.000'
union all 
select 6,2,'2007-10-4 09:00:00.000','2007-10-4 18:00:00.000'


/*存储过程*/
create proc sp_kq
(
@month int
)
as
declare @sql varchar(1000)
select @sql=''
select @sql=@sql+','''+ltrim(ttime)+'号''=min(case when day(time1)='+ltrim(ttime)+' and day(time2)='+ltrim(ttime)+' then ''出勤'' else ''缺勤'' end)'
from (select day(time1) as ttime from ta group by day(time1)) t
select @sql='select username=(select username from tb where userid=ta.userid)'+@sql+' from ta where month(time1)='+ltrim(@month)+' group by userid'
exec(@sql)

/*执行+结果*/
exec sp_kq 10

username 1号 2号 3号 4号
张三 出勤 出勤 出勤 缺勤
李四 出勤 出勤 缺勤 出勤

不知道这样满足你要求不..........

------解决方案--------------------
- - ... 你的问题真深奥...
就是动态生成列.然后判断...

完全可以写死成
select
username=(select username from tb where userid=ta.userid),
'1号'=min(case when day(time1)=1 and day(time2)=1 then '出勤' else '缺勤' end),--因为'缺勤' >'出勤' 所以用min
'2号'=min(case when day(time1)=2 and day(time2)=2 then '出勤' else '缺勤' end),
.
.
.
'31号'=min(case when day(time1)=31 and day(time2)=31 then '出勤' else '缺勤' end)
from ta group by userid where month(time1)=需要的月份

就是这个意思
我那样是写成动态去确定列...