请教各位高手,转换出错...

bdx808 2010-02-24 03:42:24
各位,新年好!
原表如下:
XH CJX CJ
012345678901 X100 88.00
012345678901 Y200 45.00
012345678901 Z500 106.05
012345678902 X100 100.00
012345678902 Z300 90.00
....

想把上表中的数据换成如下(里面不能有null,CJX有很多的):
xh X100 Y200 Z300 Z500
012345678901 88.00 45.00 106.05
012345678902 100.00 90.00

用如下行列转换代码为什么错误?
IF object_id('tb') is not null
DROP TABLE tb
go
create table tb(xh char(12) ,cjx char(10), cj numeric(6,2))
insert into tb values ('012345678901','X100',88.00)
insert into tb values ('012345678901','Y200',45.00)
insert into tb values ('012345678901','Z500',106.05)
insert into tb values ('012345678902','X100',100.00)
insert into tb values ('012345678902','Z300',90.00)
-- select * from tb

declare @sql varchar(8000)
set @sql=''
select @sql=@sql+',max(case when cjx='''+cjx+''' then cj else '''' end) as '+cjx
from tb
group by cjx

select @sql='select xh'+@sql+' into Temp from tb group by xh'
exec(@sql)
-- select * from Temp
提示:从数据类型 varchar 转换为 numeric 时出错。
...全文
35 点赞 收藏 5
写回复
5 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
bdx808 2010-02-24
多谢各位!结贴。 回复内容太短了!
回复
东那个升 2010-02-24
可否顶一下?
回复
快乐_石头 2010-02-24
--try
declare @sql varchar(8000)
set @sql=''
select @sql=@sql+',max(case when cjx='''+cjx+''' then cast(cj as varchar(10)) else '''' end) as '+cjx
from tb
group by cjx

select @sql='select xh'+@sql+' into Temp from tb group by xh'
exec(@sql)
回复
ws_hgo 2010-02-24
create table tb1(xh  char(12) ,cjx char(10), cj numeric(6,2)) 
insert into tb1 values ('012345678901','X100',88.00)
insert into tb1 values ('012345678901','Y200',45.00)
insert into tb1 values ('012345678901','Z500',106.05)
insert into tb1 values ('012345678902','X100',100.00)
insert into tb1 values ('012345678902','Z300',90.00)
-- select * from tb

declare @sql varchar(8000)
set @sql=''
select @sql=@sql+',max(case when cjx='''+cjx+''' then ltrim(cj) else '''' end) as '+cjx
from tb1
group by cjx
select @sql='select xh'+@sql+' into Temp1 from tb1 group by xh'
exec(@sql)

select * from Temp1
xh X100 Y200 Z300 Z500
------------ ----------------------------------------- ----------------------------------------- ----------------------------------------- -----------------------------------------
012345678901 88.00 45.00 106.05
012345678902 100.00 90.00

(2 行受影响)
回复
百年树人 2010-02-24
declare @sql varchar(8000)
set @sql=''
select @sql=@sql+',max(case when cjx='''+cjx+''' then ltrim(cj) else '''' end) as '+cjx
from tb
group by cjx

select @sql='select xh'+@sql+' into Temp from tb group by xh'
exec(@sql)
-- select * from Temp
/**
xh X100 Y200 Z300 Z500
------------ ---------------------------------------- ---------------------------------------- ---------------------------------------- ----------------------------------------
012345678901 88.00 45.00 106.05
012345678902 100.00 90.00

(所影响的行数为 2 行)
**/
drop table temp
回复
相关推荐
发帖
疑难问题
创建于2007-09-28

2.1w+

社区成员

MS-SQL Server 疑难问题
申请成为版主
帖子事件
创建了帖子
2010-02-24 03:42
社区公告
暂无公告