22,302
社区成员




--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)
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 行受影响)
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