最近在处理公司考勤数据时,人事部门提出要得到以下报表,具体格式如下:
 bc name     rq      sj1  sj2   sj3   sj4   
 3  张三 2011-05-05 7:00 11:15 16:25 19:15   
 3  张三 2011-05-06 6:58 11:18 16:22 19:15   
 5  李四 2011-05-06 6:53 12:18 17:22 20:13
 0  王五 2011-05-03 18:57 23:30 03:54 07:02 
而人事最基本的刷卡时间表则为以下格式
 bc   name     rq            sj
 3    张三 2011-05-05  1900-01-01 07:00
 3    张三 2011-05-05  1900-01-01 11:15
 3    张三 2011-05-05  1900-01-01 16:25
 3    张三 2011-05-05  1900-01-01 19:15
 3    张三 2011-05-06  1900-01-01 06:58
 3    张三 2011-05-06  1900-01-01 11:18
 3    张三 2011-05-06  1900-01-01 16:22      
 3    张三 2011-05-06  1900-01-01 19:15
 5    李四 2011-05-06  1900-01-01 06:53
 5    李四 2011-05-06  1900-01-01 12:18
 5    李四 2011-05-06  1900-01-01 17:22      
 5    李四 2011-05-06  1900-01-01 20:13
 0    王五 2011-05-03  1900-01-01 18:57
 0    王五 2011-05-03  1900-01-01 23:30
 0    王五 2011-05-04  1900-01-01 03:54
 0    王五 2011-05-04  1900-01-01 07:02
请大家能帮助为我把所需要的结果用SQL语句表示出来。谢谢!备注:
    因公司分好几批用餐,故用班次来区分不同的上下班时间,班次0为上夜班的。

解决方案 »

  1.   

     
    这个并非一sql之力,首先,需要在有一个记录刷卡时间所对应出勤日期,
     0 王五 2011-05-03 18:57 
     0 王五 2011-05-03 23:30
     0 王五 2011-05-04 03:54
     0 王五 2011-05-04 07-02
    这四条记录对应的出勤日期为:2011-05-03接下来就是按出勤日期分组,计算出该出勤日期的每一次刷卡是当天第n次刷卡,最后按上面的结果用case查询出来.
      

  2.   

    这个肯定有班次表,具体如下:
    bc       sj1          sj2              sj3              sj4                 sj5     5 1900-01-01 7:00  1900-01-01 11:00  1900-01-01 12:30 1900-01-01 15:30 1900-01-01 17:00
      

  3.   

    ;with cc as(
    SELECT row_number() over(PARTITION by name,worktime order by worktime,times) as oder,* from #www )
    select cc.id,cc.name,cc.worktime,  times1= max(case when id = 0 and cc.oder = 1 then cc.times when id <> 0 and cc.oder = 1 then cc.times end), --and cc.oder = 1 then cc.times else cc.times end),
    times2= max(case when id = 0 and cc.oder = 2 then cc.times when id <> 0 and cc.oder = 2 then cc.times end),
    times3= max(case when id = 0 and cc.oder = 1 then cc.times when id <> 0 and cc.oder = 3 then cc.times end),
    times4= max(case when id = 0 and cc.oder = 2 then cc.times when id <> 0 and cc.oder = 4 then cc.times end) from cc group by cc.id,cc.name,cc.worktime