难表转换?把脑壳想痛了,还是不行

table结构:时间 企业名称 流动比率 速动比率 现金比率 现金流动负债比率 现金负债比率
数据 : 2003 清华同方 3.39 1.35 0.15 10.6 5.6
2003 北大方正 3.0 1.6 0.21 15.3 6.5
2004 清华同方 4.20 1.50 0.13 12.3 6.3
2004 北大方正 3.5 1.68 0.16 14.3 6.0
转换临时表 b为:
时间 2003 2004 2003 2004
企业名称 清华同方 清华同方 北大方正 北大方正
流动比率 3.39 4.20 3.0 3.5
速动比率 1.35 1.50 1.6 1.68
现金比率 0.15 0.13 0.21 0.16
现金流动负债比率 10.6 12.3 15.3 14.3
现金负债比率 5.6 6.3 6.5 6.0

要求:建立一个去读不同表实现无论是table的字段还是它的记录都由横排转换为竖排,
有没有人做过相关的转换,给我提示吧,有代码更好!!!

---------------------------------------------------------------

create table eg(
A INT NULL,
B VARCHAR(8) NULL,
C VARCHAR(8) NULL
)
INSERT INTO EG
SELECT 1, 'long', '50' UNION ALL
SELECT 1, 'width', '20' UNION ALL
SELECT 1, 'unit', 'm' UNION ALL
SELECT 1 , 'high',''

SELECT * FROM EG
------------------------------------------------------
Declare @s varchar(300)
set @s=''
select @s=@s+B+':'+C+',' from eg where B<>'' and B is not null And C<>'' and c is not null
set @s=left(@s,len(@s)-1)
select @s
---------------------結果-----------------
长:50,宽:20,单位:米

drop table EG

---------------------------------------------------------------

--示例数据

create table tb(
时间 int,企业名称 nvarchar(10),
流动比率 decimal(10,2),速动比率 decimal(10,2),现金比率 decimal(10,2),
现金流动负债比率 decimal(10,1),现金负债比率 decimal(10,1))
insert tb select 2003,'清华同方',3.39,1.35,0.15,10.6,5.6
union all select 2003,'北大方正',3.0 ,1.6, 0.21,15.3,6.5
union all select 2004,'清华同方',4.20,1.50,0.13,12.3,6.3
union all select 2004,'北大方正',3.5 ,1.68,0.16,14.3,6.0
go

declare @s1 varchar(8000),@s2 varchar(8000)
,@s3 varchar(8000),@s4 varchar(8000),@s5 varchar(8000)
,@i varchar(10)
select @s1='',@s2='',@s3='',@s4='',@s5='',@i='0'
select @s1=@s1+',@'+@i+' varchar(8000)'
,@s2=@s2+',@'+@i+'=''时间='''''+name+''''''''
,@s3=@s3+'
,@'+@i+'=@'+@i+'+'',[''+cast(1136098324 as varchar)+'']=''''''+cast(['+name+'] as varchar)+'''''''''
,@s4=@s4+',@'+@i+'=''select ''+@'+@i
,@s5=@s5+'+'' union all ''+@'+@i
,@i=cast(@i as int)+1
from syscolumns
where object_id('tb')=id and colid>1
order by colid

select @s1=stuff(@s1,1,1,'')
,@s2=stuff(@s2,1,1,'')
,@s3=stuff(@s3,1,4,'')
,@s4=stuff(@s4,1,1,'')
,@s5=stuff(@s5,1,15,'')

exec('declare '+@s1+'
select '+@s2+'
select '+@s3+'
from tb
select '+@s4+'
exec('+@s5+')')
go

--删除测试
drop table tb

/*--结果

时间 2003 2003 2004 2004
---------------- -------- -------- -------- --------
企业名称 清华同方 北大方正 清华同方 北大方正
流动比率 3.39 3.00 4.20 3.50
速动比率 1.35 1.60 1.50 1.68
现金比率 0.15 0.21 0.13 0.16
现金流动负债比率 10.6 15.3 12.3 14.3
现金负债比率 5.6 6.5 6.3 6.0

(所影响的行数为 6 行)
--*/

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus