日期:2014-05-18  浏览次数:20507 次

sql如何转置数据表
如何在SQLserver2000中从表一转成表二形式?

表一:
-------------------------
员工 月份 数据
A 1 2000
A 2 2500
A 5 1600
A 7 2600
A 10 3000
B 1 3200
B 5 3400
B 8 5600
C 2 1100
C 3 1300
C 4 2356
C 6 1700
C 9 1200

表二
---------------------------
员工 1月 2月 3月 4月 5月 6月 7月 8月 9月 10月 11月 12月
A 2000 2500 0 0 1600 0 2600 0 0 3000 0 0
B 3200 0 0 0 3400 0 0 5600 0 0 0 0
C 0 1100 1300 2356 0 1700 0 0 1200 0 0 0


------解决方案--------------------
create table ta(员工 varchar(2),月份 int ,数据 int)
insert ta select 'A ',1,2000
union all select 'A ',2,2500
union all select 'A ',5,1600
union all select 'A ',7,2600
union all select 'A ',10,3000
union all select 'B ',1,3200
union all select 'B ',5,3400
union all select 'B ',8,5600
union all select 'C ',2,1100
union all select 'C ',3,1300
union all select 'C ',4,2356
union all select 'C ',6,1700
union all select 'C ',9,1200

declare @sql varchar(2000)
select @sql=isnull(@sql, ' ')+ ',[月份 '+rtrim(月份)+ ']=max(case 月份 when '+rtrim(月份)+ ' then rtrim(数据) else ' ' ' ' end ) '
from (select 1 as '月份 '
union select 2
union select 3
union select 4
union select 5
union select 6
union select 7
union select 8
union select 9
union select 10
union select 11
union select 12)ta
set @sql= 'select 员工 '+@sql+ ' from ta group by 员工 '
exec (@sql)

员工 月份1 月份2 月份3 月份4 月份5 月份6 月份7 月份8 月份9 月份10 月份11 月份12
---- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------
A 2000 2500 1600 2600 3000
B 3200 3400 5600
C 1100 1300 2356 1700 1200

(3 行受影响)
------解决方案--------------------
select 员工,
[1月]=sum(case when 月份=1 then 数据 else 0 end),
[2月]=sum(case when 月份=2 then 数据 else 0 end),
[3月]=sum(case when 月份=3 then 数据 else 0 end),
[4月]=sum(case when 月份=4 then 数据 else 0 end),
[5月]=sum(case when 月份=5 then 数据 else 0 end),
[6月]=sum(case when 月份=6 then 数据 else 0 end),

[7月]=sum(case when 月份=7 then 数据 else 0 end),
[8月]=sum(case when 月份=8 then 数据 else 0 end),
[9月]=sum(case when 月份=9 then 数据 else 0 end),
[10月]=sum(case when 月份=10 then 数据 else 0 end),
[11月]=sum(case when 月份=11 then 数据 else 0 end),
[12月]=sum(case when 月份=12 then 数据 else 0 end)
from tbName
group by 员工