一张记录员工出勤情况的表A:ID,UID,WORK , UID是对应员工的编号,work是出勤情况标记(int类型,对应出勤情况表中的编号)
一张为出勤情况表B:ID,WORKNAME,WORKTIME , workname是名称,worktime是每种出勤情况对应的工时(比如正常的8小时,出差的10小时,某某5小时等)
现在要查询出某员工在某一时间段内的出勤情况,可按年或按月或整个时间段统计
      
     序号   时间  出勤  请假  ..(这里要把表B里的每个情况都统计出来)...  出差  总时数      1    2012/4  2     1                ......                         3      60
时间那里如果按月的就显示  年份/月份  如果按年的就显示 年份   如果按整个时间段的就显示   年/月/日-年/月/日
这个SQL怎么写??

解决方案 »

  1.   

    表A:
    ID               time          work     uid
    1 2012/2/3 0:00:00 1 1
    2 2012/2/29 0:00:00 0 1
    3 2012/4/15 0:00:00 0 1
    4 2012/4/16 0:00:00 0 1
    5 2012/4/17 0:00:00 1 1
    6 2012/4/18 0:00:00 2 1
    45 2012/4/1 0:00:00 1 1
    46 2012/4/2 0:00:00 0 1
    47 2012/4/2 0:00:00 0 2 表B
    ID        workname         worktime
    0           到岗              8
    1           请假              0
    2           出差              10按月统计结果:
    序号   时间   到岗    请假     出差  总时数
    1     2012/2   1       1        0      8
    2     2012/4   3       2        1      34
    可能有点乱,这个编辑器看到的和显示出来的不一样,
      

  2.   

    if object_id('[TB]') is not null drop table [TB]
    go
    create table [TB] (ID int,time datetime,work int,uid int)
    insert into [TB]
    select 1,'2012/2/3 0:00:00',1,1 union all
    select 2,'2012/2/29 0:00:00',0,1 union all
    select 3,'2012/4/15 0:00:00',0,1 union all
    select 4,'2012/4/16 0:00:00',0,1 union all
    select 5,'2012/4/17 0:00:00',1,1 union all
    select 6,'2012/4/18 0:00:00',2,1 union all
    select 45,'2012/4/1 0:00:00',1,1 union all
    select 46,'2012/4/2 0:00:00',0,1 union all
    select 47,'2012/4/2 0:00:00',0,2if object_id('[TBB]') is not null drop table [TBB]
    go
    create table [TBB] (ID int,workname nvarchar(4),worktime int)
    insert into [TBB]
    select 0,'到岗',8 union all
    select 1,'请假',0 union all
    select 2,'出差',10select * from [TBB]
    select * from [TB]
    select uid,convert(varchar(7),time,120) as time,
    sum(case when TB.work =0 then 1 else 0 end) as '到岗',
    sum(case when TB.work =1 then 1 else 0 end) as '请假',
    sum(case when TB.work =2 then 1 else 0 end) as '出差'
    from TB
    left join TBB on TB.work = TBB.ID
    group by uid,convert(varchar(7),time,120)
    /*
    1 2012-02 1 1 0
    1 2012-04 3 2 1
    2 2012-04 1 0 0
    */