我对不同的表有类似的 3-4 个脚本来动态 PIVOT,就像之前发布的 Dynamic Pivot (row to columns)
目标: - 创建一个 excel 文件连接 PIVOTed 表中的所有字段(每个表中的所有行)
脚步:
为每个集合创建单独的临时表(在不同表上进行透视之后)
加入列 ID 上的所有临时表
从结果集中选择列(所有临时表)
**想知道是否有更好的方法来创建临时表,该方法使用连接所有表以进行最终选择的过程。
**我尝试创建临时表但收到错误:无效对象
由于上一篇文章中接受的答案**
INSERT into #T1 execute('execute' + @query )
select * from #T1
**
案例 1:在您的桌子上旋转
DECLARE @query AS NVARCHAR(MAX),
@colsPivot as NVARCHAR(MAX)
select @colsPivot = STUFF((SELECT ','
+ quotename('Instance'+ cast(instance as varchar(10))+'_'+c.name)
from yourtable t
cross apply sys.columns as C
where C.object_id = object_id('yourtable') and
C.name not in ('id', 'instance')
group by t.instance, c.name
order by t.instance
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'select *
from
(
select id,
''Instance''+cast(instance as varchar(10))+''_''+col col,
value
from
(
select id,
Instance,
Name,
cast(Size as varchar(50)) Size,
Tech
from yourtable
) x
unpivot
(
value
for col in (Name, Size, Tech)
) u
) x1
pivot
(
max(value)
for col in ('+ @colspivot +')
) p'
--exec(@query)
我尝试创建临时表,但由于上一篇文章中接受的答案而得到错误:无效对象
INSERT into #T1 execute('execute' + @query )
select * from #T1
案例 2:MYtable 的相同代码 PIVOT
DECLARE @query AS NVARCHAR(MAX),
@colsPivot as NVARCHAR(MAX)
select @colsPivot = STUFF((SELECT ','
+ quotename('Instance'+ cast(instance as varchar(10))+'_'+c.name)
from mytable t
cross apply sys.columns as C
where C.object_id = object_id('yourtable') and
C.name not in ('id', 'instance')
group by t.instance, c.name
order by t.instance
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'select *
from
(
select id,
''Instance''+cast(instance as varchar(10))+''_''+col col,
value
from
(
select id,
Instance,
Name,
cast(Size as varchar(50)) Size,
Tech
from mytable
) x
unpivot
(
value
for col in (Name, Size, Tech)
) u
) x1
pivot
(
max(value)
for col in ('+ @colspivot +')
) p'
INSERT into #T2 execute('execute' + @query2 )
select * from #T2
** 案例 3:OurTable 的相同代码 PIVOT**
DECLARE @query AS NVARCHAR(MAX),
@colsPivot as NVARCHAR(MAX)
select @colsPivot = STUFF((SELECT ','
+ quotename('Instance'+ cast(instance as varchar(10))+'_'+c.name)
from ourtable t
cross apply sys.columns as C
where C.object_id = object_id('yourtable') and
C.name not in ('id', 'instance')
group by t.instance, c.name
order by t.instance
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'select *
from
(
select id,
''Instance''+cast(instance as varchar(10))+''_''+col col,
value
from
(
select id,
Instance,
Name,
cast(Size as varchar(50)) Size,
Tech
from ourtable
) x
unpivot
(
value
for col in (Name, Size, Tech)
) u
) x1
pivot
(
max(value)
for col in ('+ @colspivot +')
) p'
INSERT into #T3 execute('execute' + @query2 )
select * from #T3
最终选择:
select * from #T1
inner join #T1.id=#T2.id
inner join #T1.id=#T3.id