超小问题,马上解决,马上给分,谢谢大家
现有考勤表A
ID(id) 用户名(name) 考勤类型(int sort) 考勤时间(time) 部门( int dept)
1 张三 1(迟到) 2005-05-05 3(市场部)
2 李四 1(迟到) 2005-06-05 2(开发部)
3 张三 2(旷工) 2005-05-05 3(市场部)
4 李四 2(旷工) 2005-06-05 3(市场部)
考勤分类表B
bid 考勤类型
1 迟到
2 旷工
3 早退
4 病假
... ...
如何按时间或部门分类汇总:
用户名 迟到 旷工 早退 病假
张三 1 1 0 0 //数字表示次数
李四 1 2 0 0
[解决办法]
create table 考勤表A (id int,name nvarchar(30), sort int, 考勤时间 datetime , dept int )
insert 考勤表A
select 1,N '张三 ' , 1 , 2005-05-05 , 3
union select 2, N '李四 ' , 1, 2005-06-05 , 2
union select 3, N '张三 ' , 2, 2005-05-05 , 3
union select 4,N '李四 ' , 2, 2005-06-05 , 3
create table 考勤分类表B (bid int, 考勤类型 nvarchar(10))
insert 考勤分类表B
select 1 , N '迟到 '
union select 2 , N '旷工 '
union select 3 , N '早退 '
union select 4 , N '病假 '
select 用户名=a.name,
迟到=sum(case when sort=1 then 1 else 0 end) ,
旷工=sum(case when sort=2 then 1 else 0 end) ,
早退=sum(case when sort=3 then 1 else 0 end) ,
病假=sum(case when sort=4 then 1 else 0 end)
from 考勤表A a inner join 考勤分类表B b on a.sort=b.bid
group by a.name
drop table 考勤表A,考勤分类表B
[解决办法]
if object_id( 'tbTest ') is not null
drop table tbTest
if object_id( 'tbType ') is not null
drop table tbType
GO
create table tbTest(ID int,name varchar(10),sort int,time varchar(10),dept int)
insert tbTest
select 1, '张三 ', 1, '2005-05-05 ', 3 union all
select 2, '李四 ', 1, '2005-06-05 ', 2 union all
select 3, '张三 ', 2, '2005-05-05 ', 3 union all
select 4, '李四 ', 2, '2005-06-05 ', 3
create table tbType(bid int,考勤类型 varchar(10))
insert tbType
select 1, '迟到 ' union all
select 2, '旷工 ' union all
select 3, '早退 ' union all
select 4, '病假 '
GO
[解决办法]
参考
create table tab (姓名 varchar(20),项目 varchar(1), 金额 int)
insert into tab values( 'a ', '1 ',66)
insert into tab values( 'a ', '2 ',44)
insert into tab values( 'b ', '1 ',88)
insert into tab values( 'b ', '2 ',99)
select * from tab
declare @sql varchar(max)
set @sql= 'select 姓名, '
select @sql=@sql+ 'sum(case when 项目= ' ' '+ 项目+ ' ' ' then 金额 else 0 end ) as 项目 '+ 项目 + ', ' from tab group by 项目
set @sql=left(@sql,len(@sql)-1)+ ' from tab group by 姓名 '
exec(@sql)
drop table tab
[解决办法]
create table a
(
id int identity(1,1),
name varchar(5),
sort int ,
time datetime,
dept int
)
go
insert into a
select '张三 ',1, '2005-05-05 ',3 union all
select '李四 ',2, '2005-06-05 ',2 union all
select '张三 ',2, '2005-05-05 ',3 union all
select '李四 ',2, '2005-06-05 ',3
go
create table b
(
bid int identity(1,1),
tp varchar(5)
)
insert into b
select '迟到 ' union all
select '旷工 ' union all
select '早退 ' union all
select '病假 '
go
declare @sql varchar(500)
set @sql= 'select name '
select @sql=@sql+ ',sum(case tp when ' ' '+tp+ ' ' 'then 1 else 0 end) as ' +tp from
(select distinct tp from b) tb
set @sql =@sql+ ' from (select a.*,b.tp from a left outer join b on a.sort=b.bid) tb group by name '--此处按部门统计改为group by dept,name,按时间将where 条件更改一下 where time between ...and ....
exec (@sql)
name 病假 迟到 旷工 早退
----- ----------- ----------- ----------- -----------
李四 0 0 2 0
张三 0 1 1 0
(2 行受影响)