⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 复杂交叉表.sql

📁 sqlserver 数据库编程的绝好脚本
💻 SQL
字号:
--测试

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

--处理
select id=0,* into #t from 表 order by 编号,分类一--,分类二,分类三
declare @a varchar(10),@i int
update #t set @i=case @a when 分类一 then @i+1 else 0 end,id=@i,@a=分类一

declare @fd varchar(8000),@s varchar(8000)
	,@t1 varchar(10),@t2 varchar(10)
select @fd='',@s='',@t1='',@t2=''
select @t2='['+分类一+']'
	,@fd=@fd+','+@t2+'=isnull('+@t2+'.分类二,''''),'+@t2+'=isnull('+@t2+'.分类三,'''')'
	,@s=case @t1 when '' then '(select * from #t where 分类一='''+分类一+''')'+@t2 
		else @s+' full join(select * from #t where 分类一='''+分类一+''')'+@t2+' on '+@t1+'.id='+@t2+'.id ' end
	,@t1=@t2
from #t group by 分类一

select @fd=substring(@fd,2,8000)
exec('select '+@fd+'
from '+@s)

--删除处理临时表
drop table #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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -