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

这样的想法能实现吗?
表A的数据如下:

name               sex               age       monthwage
'张三 '           ‘男’         28           1000
'李四 '           ‘男’         25           800

通过什么方法可以转置得到如下结果:
 
'张三 '         ‘李四’
‘男’           '男 '
  28                   25  
  1000               800

请大家帮一下忙。谢谢了!


------解决方案--------------------
或用行列轉換
------解决方案--------------------
--建立测试表:

create table tb (
name varchar(10),
sex varchar(2),
age int,
monthwageas int)
go
--生成测试数据:

insert tb select
'张三 ' , '男 ' , 28 , 1000
union all
select '李四 ' , '男 ' , 25 , 800
union all
select '王丽 ', '女 ',18,600

--建立转换过程:
create proc proc_temp0510
as
begin
set nocount on
select * into #t
from
(select 1 as row,cast(name as varchar(128)) data,1 as col from tb
union all
select 2 as row,cast(sex as varchar(128)) data,1 from tb
union all
select 3 as row,cast(age as varchar(128)) data,1 from tb
union all
select 4 as row,cast(monthwageas as varchar(128)) data,1 from tb)a

declare @i int,@row int
update #t set @i=case row when @row then @i+1 else 1 end,col = @i, @row = row

declare @sql varchar(8000),@sql1 varchar(2000),@sql2 varchar(2000),@sql3 varchar(2000)

select @sql = ' ',@sql1 = 'select ',@sql2 = ' where ',@sql3 = ' from '
declare @j int
set @j = 1
while @j <=@i
begin

select @sql = @sql + ' declare @t '+cast(@j as varchar)+ ' table(row int,data varchar(128)) '+char(10)
select @sql = @sql + ' insert into @t '+cast(@j as varchar)+ ' select row, data from #t where col = '+cast(@j as varchar)+char(10)
select @sql1 = @sql1+ 'a '+cast(@j as varchar)+ '.data '+case @j when @i then ' ' else ', ' end
select @sql3 = @sql3+ ' @t '+cast(@j as varchar)+ ' a '+cast(@j as varchar)+case @j when @i then ' ' else ', ' end
select @sql2 = @sql2 +case @j when 1 then 'a1.row = ' when @i then 'a '+cast(@j as varchar)+ '.row ' else 'a '+cast(@j as varchar)+ '.row and a '+cast(@j as varchar)+ '.row= ' end
select @j = @j+1

end
select @sql = @sql+@sql1+char(10)+@sql3+char(10)+@sql2
--print @sql
exec( @sql)
end

--执行过程:
exec proc_temp0510
--执行结果:
张三 李四 王丽
男 男 女
28 25 18
1000 800 600

------解决方案--------------------
用SQL进行转换有点麻烦.
LZ在程序端实现吧.