现在的位置: 首页 > 综合 > 正文

行值动态变化的交叉表转换多列处理示例

2014年03月19日 ⁄ 综合 ⁄ 共 1640字 ⁄ 字号 评论关闭

--测试

 

--测试数据

create table (编号 int,分类一 varchar(10),分类二 varchar(10),分类三 varchar(10))

insert select 1,'M1','D1','F1'

union all select 1,'M1','D2','F2'

 

union all select 1,'M2','D3','F3'

union all select 1,'M2','D3','F4'

union all select 1,'M2','D3','F5'

union all select 1,'M2','D4','F2'

union all select 1,'M2','D4','F7'

union all select 1,'M2','D5','F1'

union all select 1,'M2','D5','F3'

 

union all select 1,'M3','D6','F8'

union all select 1,'M3','D7','F6'

go

 

--处理方法2.

declare @s varchar(8000)

select @s=''

select @s=@s+',['+分类一+'_1] varchar(10) default '''',['

    +分类一+'_2] varchar(10) default '''''

from group by 分类一

 

exec('create table #t(id int identity(1,1)'+@s+')

declare @s varchar(8000)

declare tb cursor local for select s=''declare @t table(id int identity(1,1),a varchar(10),b varchar(10))

declare @r int

insert @t select 分类二,分类三 from where 分类一=''''''+分类一+''''''

set @r=@@rowcount

update #t set [''+分类一+''_1]=b.a,[''+分类一+''_2]=b.b

from #t a join @t b on a.id=b.id

if @@rowcount<@r

    insert #t([''+分类一+''_1],[''+分类一+''_2]) select a.a,a.b

    from @t a left join #t b on a.id=b.id

    where b.id is null''

from group by 分类一

open tb

fetch next from tb into @s

while @@fetch_status=0

begin

    exec(@s)

    fetch next from tb into @s

end

close tb

deallocate tb

select * from #t

')

go

 

--删除测试

drop table

 

/*--测试结果

M1         M1         M2         M2         M3         M3        

---------- ---------- ---------- ---------- ---------- ----------

D1         F1         D3         F3         D6         F8

D2         F2         D3         F4         D7         F6

                      D3         F5                   

                      D4         F2                   

                      D4         F7                    

                      D5         F1                   

                      D5         F3                   

 

--*/

 

抱歉!评论已关闭.