C 210 1 C 130 2 ..... 转化成 表2 编号 序号1 序号2 序号3 B 100 150 160 C 210 130 用什么办法把表1中的数据弄到表2中,且速度比较快?? --上面写错了一个关键字,改一下: declare @s varchar(8000) set @s='' select @s=@s+',[序号'+序号+']=sum(case 序号 when '+序号+' then 值 else 0 end)' from(select distinct 序号=cast(序号 as varchar) from 表1) a
--如果表2已经存在 exec('insert into 表2 select 编号'+@s+' from 表1 group by 编号')
--如果表2不存在 exec('select 编号'+@s+' into 表2 from 表1 group by 编号')--下面是查询得到结果的例子:
--测试数据 create table 表1(编号 varchar(1),值 int,序号 int) insert into 表1 select 'B',100,1 union all select 'B',150,2 union all select 'B',160,3 union all select 'C',210,1 union all select 'C',130,2
--查询处理 declare @s varchar(8000) set @s='' select @s=@s+',[序号'+序号+']=sum(case 序号 when '+序号+' then 值 else 0 end)' from(select distinct 序号=cast(序号 as varchar) from 表1) a exec('select 编号'+@s+' from 表1 group by 编号') go
--删除测试表 drop table 表1 go
/*--测试结果
编号 序号1 序号2 序号3 ---- ----------- ----------- ----------- B 100 150 160 C 210 130 0
DataTable dt1 = dt.Copy();
去试下
表1
编号 值 序号
B 100 1
B 150 2
B 160 3
C 210 1
C 130 2
.....
转化成
表2
编号 序号1 序号2 序号3
B 100 150 160
C 210 130
用什么办法把表1中的数据弄到表2中,且速度比较快??
--上面写错了一个关键字,改一下:
declare @s varchar(8000)
set @s=''
select @s=@s+',[序号'+序号+']=sum(case 序号 when '+序号+' then 值 else 0 end)'
from(select distinct 序号=cast(序号 as varchar) from 表1) a
--如果表2已经存在
exec('insert into 表2 select 编号'+@s+' from 表1 group by 编号')
--如果表2不存在
exec('select 编号'+@s+' into 表2 from 表1 group by 编号')--下面是查询得到结果的例子:
--测试数据
create table 表1(编号 varchar(1),值 int,序号 int)
insert into 表1
select 'B',100,1
union all select 'B',150,2
union all select 'B',160,3
union all select 'C',210,1
union all select 'C',130,2
--查询处理
declare @s varchar(8000)
set @s=''
select @s=@s+',[序号'+序号+']=sum(case 序号 when '+序号+' then 值 else 0 end)'
from(select distinct 序号=cast(序号 as varchar) from 表1) a
exec('select 编号'+@s+' from 表1 group by 编号')
go
--删除测试表
drop table 表1
go
/*--测试结果
编号 序号1 序号2 序号3
---- ----------- ----------- -----------
B 100 150 160
C 210 130 0
--*/
具体的你去万网的网站上找找吧