求sql语句:如何将行集以一行多列的形式显示出来?
例如:
表CostType结构为:
TypeId,TypeName
101 费用1
102 费用2
.
.
.
如何将它转换显示为如下结果:
101 102 . . . .
费用1 费用2 . . . .
高手请出手!!!
问题点数:50、回复次数:13Top
1 楼zjcxc(邹建)回复于 2004-09-02 15:01:41 得分 10
declare @s varchar(8000)
set @s=''
select @s=@s+',['+cast(TypeId as varchar)+']='''+TypeName+''''
from CostType
set @s=stuff(@s,1,1,'')
exec('select '+@s)Top
2 楼netcoder(朱二)回复于 2004-09-02 15:02:54 得分 5
select [101]='费用1' ,[102]='费用2',……Top
3 楼zjcxc(邹建)回复于 2004-09-02 15:02:57 得分 10
--测试
declare @s varchar(8000)
set @s=''
select @s=@s+',['+cast(TypeId as varchar)+']='''+TypeName+''''
from(
select TypeId=101,TypeName='费用1'
union all select 102,'费用2'
)CostType
set @s=stuff(@s,1,1,'')
exec('select '+@s)
/*--测试结果
101 102
----- -----
费用1 费用2
--*/Top
4 楼jimmyxing(积极进取)回复于 2004-09-02 15:06:01 得分 0
真是高手阿!多谢多谢。
Top
5 楼jimmyxing(积极进取)回复于 2004-09-02 15:13:26 得分 0
不过有个问题阿,CostType中数据行数是不固定的阿,需要动态变化Top
6 楼zjcxc(邹建)回复于 2004-09-02 15:15:11 得分 10
你测试了就知道了. 我写的本来就是处理不固定数据的Top
7 楼jimmyxing(积极进取)回复于 2004-09-02 15:18:48 得分 0
不行阿,再增加一条记录就不行了。如:
TypeId,TypeName
101 费用1
102 费用2
103 费用3
.
.
.
就不行了
Top
8 楼zjcxc(邹建)回复于 2004-09-02 15:20:36 得分 10
--倒,你怎么测试的??
--测试
declare @s varchar(8000)
set @s=''
select @s=@s+',['+cast(TypeId as varchar)+']='''+TypeName+''''
from(
select TypeId=101,TypeName='费用1'
union all select 102,'费用2'
union all select 103,'费用3'
union all select 104,'费用4'
union all select 105,'费用5'
union all select 106,'费用6'
union all select 107,'费用7'
union all select 108,'费用8'
union all select 109,'费用9'
)CostType
set @s=stuff(@s,1,1,'')
exec('select '+@s)
/*--测试结果
101 102 103 104 105 106 107 108 109
----- ----- ----- ----- ----- ----- ----- ----- -----
费用1 费用2 费用3 费用4 费用5 费用6 费用7 费用8 费用9
--*/
Top
9 楼zjcxc(邹建)回复于 2004-09-02 15:22:06 得分 5
--如果 TypeName 是char的
declare @s varchar(8000)
set @s=''
select @s=@s+',['+rtrim(cast(TypeId as varchar))+']='''+rtrim(TypeName)+''''
from CostType
set @s=stuff(@s,1,1,'')
exec('select '+@s)Top
10 楼gaodongsheng(东升)回复于 2004-09-02 15:33:26 得分 0
老大写的怎么会有问题呢!!Top
11 楼jimmyxing(积极进取)回复于 2004-09-02 15:34:43 得分 0
噢,我没有说清除。CostType表中的记录是不确定的。换句话说
select TypeId=101,TypeName='费用1'
union all select 102,'费用2'
union all select 103,'费用3'
union all select 104,'费用4'
union all select 105,'费用5'
union all select 106,'费用6'
union all select 107,'费用7'
union all select 108,'费用8'
union all select 109,'费用9'
这些语句是要根据表中记录的多少自动生成的,而且其中的数据101,102...和费用1,费用2...都是要根据CostType表中的记录来确定的。Top
12 楼zjcxc(邹建)回复于 2004-09-02 15:39:19 得分 0
请问楼主一下,你去测试了吗????
declare @s varchar(8000)
set @s=''
select @s=@s+',['+rtrim(cast(TypeId as varchar))+']='''+rtrim(TypeName)+''''
from CostType
set @s=stuff(@s,1,1,'')
exec('select '+@s)
Top
13 楼jimmyxing(积极进取)回复于 2004-09-02 19:03:18 得分 0
SQLServer里是可以,不知道Access里怎么办?Access支持的东西好像太少了。Top




