日期:2014-05-17  浏览次数:20421 次

给出一个表打横建成另外一张表
本帖最后由 chenfeng_cstp 于 2013-08-29 19:37:36 编辑
现:表1
aa        bb     cc
HR知识   2.0 自我评价
HR知识   2.0 上级评价
财务知识   2.0 自我评价
财务知识   1.0 上级评价
分析与诊断  2.0 自我评价
分析与诊断  2.0 上级评价
目标管理知  2.0 自我评价


需要实现结果:表2
cc            HR知识         财务知识          分析与诊断          目标管理知
自我评价          2.0            2.0            2.0              2.0
上级评价          2.0            1.0            2.0

最好能够做成通用型语句,
打横最后能够随便制定一列,做表头
实用

------解决方案--------------------

create table #tb(aa varchar(20),bb numeric(5,1),cc varchar(20))
insert into #tb
select 'HR知识',2.0,'自我评价'
union all select 'HR知识',2.0,'上级评价'
union all select '财务知识',2.0,'自我评价'
union all select '财务知识',1.0,'上级评价'
union all select '分析与诊断',2.0,'自我评价'
union all select '分析与诊断',2.0,'上级评价'
union all select '目标管理知',2.0,'自我评价'

declare @sql varchar(8000)
set @sql=''
select @sql=@sql + ',['+rtrim(aa)+']=max(case rtrim(aa) when '''+rtrim(aa)+''' then bb end)'
from #tb group by rtrim(aa)
exec('select cc'+@sql+' from #tb group by cc')


/*
cc HR知识 财务知识 分析与诊断 目标管理知
上级评价 2.0 1.0 2.0 NULL
自我评价 2.0 2.0 2.0 2.0
*/
------解决方案--------------------
if OBJECT_ID('tempdb..#temp', 'u') is not null   drop table #temp;