请教关于SQL交叉 插入数据
比如现在有2张表T1和T2 T1表为 T2表为空表 表头是:
案号 工作模块 时间 案号 A B C D E F G H I J
001 A 6
002 B 7
002 C 1
003 J 3
003 I 4
执行结果为
案号 A B C D E F G H I J
001 6
002 7 1
003 4 3
大致就是这个样子
结果要保存到表T2中,表中空的单元值为null
程序代码:declare @a int
....
@j int
@count int
@ n int
@anhao varchar(20)--对应于字段案号
set @n=1
select @count=count(*) from T1
select 案号,工作模块,时间,identity(int,1,1) as ID
into a
from T1 order by 案号--创建一个新表,添加一个字段ID用来逐条取出记录,并用案号排序,使得相同案号的记录挨在一起
while(@n<=@count)
begin
select @anhao=案号,case 工作模块
when 'A' then @a=时间
when 'B' then @b=时间
when 'C' then @c=时间
when 'D' then @d=时间
when 'E' then @e=时间
when 'F' then @f=时间
when 'G' then @g=时间
when 'H' then @h=时间
when 'I' then @i=时间
when 'J' then @j=时间
from a where a.ID=@n
while(true)--这个循环用来将T1表中相同案号的不同记录时间添加到同一条插入记录中
begin
@n=@n+1
if(select 案号 from a where ID=@n)=@anhao
begin
select case 工作模块
when 'A' then @a=时间
when 'B' then @b=时间
when 'C' then @c=时间
when 'D' then @d=时间
when 'E' then @e=时间
when 'F' then @f=时间
when 'G' then @g=时间
when 'H' then @h=时间
when 'I' then @i=时间
when 'J' then @j=时间
from a where a.ID=@n
end
else
break
end
insert into T2
values(@anhao,@a,@b,@c,@d,@e,@f,@g,@h,@i,@j)
end
drop table a