日期:2014-05-18 浏览次数:20508 次
select 员工ID, max(case 月份 when 4 then 考勤天数 else 0 end) as 4月, max(case 月份 when 3 then 考勤天数 else 0 end) as 3月, max(case 月份 when 2 then 考勤天数 else 0 end) as 2月 from tb group by 员工ID
------解决方案--------------------
只是月份的话 一般做法都是一个一个判断 然后合计 也可以使用存储 动态sql拼接起来
------解决方案--------------------
--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
create table [test]([考勤天数] int,[员工ID] varchar(1),[月份] int)
insert [test]
select 28,'A',4 union all
select 26,'A',3 union all
select 25,'A',2 union all
select 28,'B',3 union all
select 26,'B',2 union all
select 27,'C',4 union all
select 30,'C',3 union all
select 27,'C',2
--我写一个动态的
declare @str varchar(2000)
set @str=''
select
@str=@str+',['+LTRIM([月份])+'月]=max(case when [月份]='
+ltrim([月份])+' then [考勤天数] else 0 end)'
from
[test]
group by
[月份]
exec('select [员工ID]'+@str+' from test group by [员工ID]')
/*
员工ID 2月 3月 4月
-------------------------------
A 25 26 28
B 26 28 0
C 27 30 27
*/