我有一个SQL 2008表,其中包含了每台计算机的一行,其中包含了多列软件标题:
Computer Col1 Col2 Col3 Col4
PC1 Acrobat Word Excel
PC2 Word Access
PC3 Google
PC4 Word Excel SQL2008 Maximizer我想把它合并成这样的两列:
Computer Software
PC1 Acrobat
PC1 Word
PC1 Excel
PC2 Word
PC2 Access
PC3 Google
PC4 Word
PC4 Excel
PC4 SQL2008
PC4 Maximizer它不是列的集合,所以卸载或转置工作吗?
每一行有1到32列的数据。软件名称有数百个不同的值。
发布于 2013-09-04 18:27:02
您可以通过几种不同的方式解除数据的枢轴,包括unpivot函数或交叉应用,以将多列转换为行。
UNPIVOT
select computer, software
from yourtable
unpivot
(
software
for col in ([Col1], [Col2], [Col3], [Col4])
) un;见与Demo。
交叉应用:
select t.computer, c.software
from yourtable t
cross apply
(
select col1 union all
select col2 union all
select col3 union all
select col4
) c (software)
where c.software is not null;见与Demo。还可以根据Server的版本使用交叉应用和值:
select t.computer, c.software
from yourtable t
cross apply
(
values
(col1), (col2),
(col3), (col4)
) c (software)
where c.software is not null;请参阅与Demo
https://stackoverflow.com/questions/18621112
复制相似问题