复杂交叉表1.sql

来自「关于Sql的一些命令的源代码」· SQL 代码 · 共 69 行

SQL
69
字号
--测试

--测试数据
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                    

--*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?