| 发表于:2007-06-28 10:27:0111楼 得分:0 |
create table a(id int,name nvarchar(10),sort int,time varchar(10),dept int) insert a select 1, n '张三 ', 1, '2005-05-05 ', 3 union all select 2, n '李四 ', 1, '2005-06-05 ', 2 union all select 3, n '张三 ', 2, '2005-05-05 ', 3 union all select 4, n '李四 ', 2, '2005-06-05 ', 3 create table b(bid int,考勤类型 nvarchar(10)) insert b select 1, n '迟到 ' union all select 2, n '旷工 ' union all select 3, n '早退 ' union all select 4, n '病假 ' go --如果考勤类型是固定的 select a.name, sum(case b.考勤类型 when n '迟到 ' then 1 else 0 end) as 迟到, sum(case b.考勤类型 when n '旷工 ' then 1 else 0 end) as 旷工, sum(case b.考勤类型 when n '早退 ' then 1 else 0 end) as 早退, sum(case b.考勤类型 when n '病假 ' then 1 else 0 end) as 病假 from a inner join b on a.sort = b.bid group by a.name --如果考勤类型不是固定的 declare @s nvarchar(4000) select @s = ' select a.name ' select @s = @s + n ',sum(case b.考勤类型 when n ' ' ' + 考勤类型 + ' ' ' then 1 else 0 end) as ' + 考勤类型 from b order by bid select @s = @s + ' from a inner join b on a.sort = b.bid group by a.name ' EXEC(@s) go drop table a, b --result /* name 迟到 旷工 早退 病假 李四 1 1 0 0 张三 1 1 0 0 */ | | |
|