SQL Server 2008 R2,将列转换为行,将行转换为列[重复]
Posted
技术标签:
【中文标题】SQL Server 2008 R2,将列转换为行,将行转换为列[重复]【英文标题】:SQL Server 2008 R2, convert columns to rows and rows to columns [duplicate] 【发布时间】:2013-08-19 09:10:34 【问题描述】:表中的当前数据
id AA BB CC DD EE FF
1 a b c d e f
2 a1 b2 c3 d2 e4 f2
我想:
Colx 1 2
AA a a1
BB b b2
CC c c3
DD d d2
EE e e4
FF f f2
请帮帮我。
【问题讨论】:
【参考方案1】:好吧,仔细看了你的问题,我认为这不是重复的,你不仅想将列转换为行,还想同时将行转换为列。 因此,您必须结合两种解决方案 - 将列转为行并将行转为列,例如:
select
c.name as ColX,
max(case when t.id = 1 then c.value else null end) as [1],
max(case when t.id = 2 then c.value else null end) as [2]
from Table1 as t
cross apply (values
('AA', t.AA),
('BB', t.BB),
('CC', t.CC),
('DD', t.EE)
) as c(name, value)
group by c.name
sql fiddle demo
您也可以使用 SQL Server 中的standard pivot and unpivot:
select *
from Table1 as t
unpivot (
value for
colx in (AA, BB, CC, DD, EE, FF)
) as unpiv
pivot (
max(unpiv.value)
for id in ([1], [2])
) as piv
sql fiddle demo
如果不想指定 id 和 columns 的值,试试动态 SQL:
declare @stmt1 nvarchar(max), @stmt2 nvarchar(max), @stmt nvarchar(max)
select @stmt1 =
isnull(@stmt1 + ', ', '') +
'(''' + c.column_name + ''', t.' + c.column_name + ')'
from information_schema.columns as c
where c.table_name = 'Table1' and c.column_name <> 'id'
select @stmt2 =
isnull(@stmt2 + ', ', '') + 'max(case when t.id = ' + t.id + ' then c.value end) as [' + t.id + ']'
from (select distinct cast(id as nvarchar(max)) as id from Table1) as t
select @stmt = '
select
c.name as ColX, ' + @stmt2 + '
from Table1 as t
cross apply (values ' + @stmt1 + ') as c(name, value)
group by c.name'
exec sp_executesql @stmt = @stmt
sql fiddle demo
【讨论】:
谢谢 Roman Pekar,但 id 无法修复,请再次提供帮助。 很好的解决方案,非常感谢。以上是关于SQL Server 2008 R2,将列转换为行,将行转换为列[重复]的主要内容,如果未能解决你的问题,请参考以下文章