如何使用 T-SQL 透视表?
Posted
技术标签:
【中文标题】如何使用 T-SQL 透视表?【英文标题】:How to pivot table with T-SQL? 【发布时间】:2012-04-07 12:38:24 【问题描述】:如何从这种格式转换表格:
Id | Data |Section
------------------------------------------
1 |1AAA |AAA
------------------------------------------
1 |1BBB |BBB
------------------------------------------
1 |1CCC |CCC
------------------------------------------
2 |2AAA |AAA
------------------------------------------
2 |2BBB |BBB
------------------------------------------
2 |2CCC |CCC
------------------------------------------
3 |3AAA |AAA
------------------------------------------
3 |3CCC |CCC
------------------------------------------
用 T-sql 转成这种格式?
Id |Column_AAA|Column_BBB|Colunm_CCC|
-------------------------------------
1 |1AAA |1BBB |1CCC |
-------------------------------------
2 |2AAA |2BBB |2CCC |
-------------------------------------
3 |3AAA |..... |3CCC |
【问题讨论】:
【参考方案1】:这应该会给你想要的结果。
CREATE TABLE #temp
(
id int,
data varchar(50),
section varchar(50)
)
insert into #temp values(1, '1AAA', 'AAA')
insert into #temp values(1, '1BBB', 'BBB')
insert into #temp values(1, '1CCC', 'CCC')
insert into #temp values(2, '2AAA', 'AAA')
insert into #temp values(2, '2BBB', 'BBB')
insert into #temp values(2, '2CCC', 'CCC')
insert into #temp values(3, '3AAA', 'AAA')
insert into #temp values(3, '3BBB', 'BBB')
insert into #temp values(3, '3CCC', 'CCC')
select id, [AAA] as Column_AAA, [BBB] as Column_BBB, [CCC] as Column_CCC
from
(
select id, data, section
from #temp
) x
PIVOT
(
max(data)
FOR section IN([AAA], [BBB], [CCC])
) as p
drop table #temp
结果:
id column_AAA column_BBB column_CCC
1 1AAA 1BBB 1CCC
2 2AAA 2BBB 2CCC
3 3AAA 3BBB 3CCC
【讨论】:
以上是关于如何使用 T-SQL 透视表?的主要内容,如果未能解决你的问题,请参考以下文章