SQL Server实现表格转置的技术实现(sqlserver表转置)
SQL Server转置表是一种允许用户将表格中的行转换成列等技术实现,通过该技术,可以开发出更好地报表,更加美观地展示数据。
SQL Server的转置表主要有两种实现方式:1.使用内置的PIVOT及UNPIVOT函数;2.使用简单的TOP查询。
使用内置的PIVOT及UNPIVOT函数可以实现SQL Server表格转置。比如:
–create a sample table
create table testpivot
(
name varchar(20),
A int,
B int,
C int
)
–insert some dummy data
insert into testpivot values(‘Jack’,1,2,3),(‘Mary’,4,5,6)
–Transpose a table
select * from
(
select name,A,B,C from testpivot
) as src
pivot
(
Sum(name)
for name in ([A],[B],[C])
) as piv
使用简单的TOP查询也可以实现SQL Server表格转置,它的实现步骤如下:
1.创建一个存储行逻辑的临时表;
2.使用TOP查询扩充新的列;
3.将行逻辑的临时表行转换为列;
例如:
–Create a temporary table to store row logic
select * into #TMPTEST
from testpivot
–expand the table and add new columns
select name,A,B,C,
(SELECT TOP 1 B FROM #TMPTEST WHERE name=T.name) as BValue,
(SELECT TOP 1 C FROM #TMPTEST WHERE name=T.name) as CValue
into #TMPTEST2
from #TMPTEST T
–Transpose the table
select * from
(
SELECT Name,A,BValue,CValue FROM #TMPTEST2
) as src
pivot
(
Sum(Name) for Name in ([A],[BValue],[CValue])
) as piv
这两种方式均可实现SQL Server表格转置,可以根据需求Mathod.1或Mathod.2的实现方式。