SQL SERVER中PIVOT和UNPIVOT
PIVOT和UNPIVOT
PIVOT 通过将表达式某一列中的唯一值转换为输出中的多个列来旋转表值表达式,并在必要时对最终输出中所需的任何其余列值执行聚合。UNPIVOT 与 PIVOT 执行相反的操作,将表值表达式的列转换为列值。
基本准备:
create table TestPivot
(
name varchar(50)
)
insert into testpivot(name)
select 'DePaul'
union all
select 'DePaul'
union all
select 'LeeWhoeeUniversity'
union all
select 'LeeWhoeeUniversity'
union all
select 'LeeWhoee'
union all
select 'LeeWhoee'
union all
select 'LeeWhoee'用下面的查询当做一个表来操作
select name,count(*) as totalcount from testpivot
group by name运行结果:
name totalcount
LeeWhoee 3
DePaul 2
LeeWhoeeUniversity 2
上面是我们将要操作的表数据
PIVOT
select 'totalcount' as name,[LeeWhoee],[DePaul],[LeeWhoeeUniversity]
from
(
select name,count(*) as totalcount from testpivot
group by name
) a
pivot
(
max(totalcount) for name in ([LeeWhoee],[LeeWhoeeUniversity],[DePaul])
) b运行结果:
name LeeWhoee DePaul LeeWhoeeUniversity
totalcount 3 2 2
UNPIVOT
下面使用UNPIVOT将此结果集反转成初始结果集
select _name as name,_totalcount as totalcount
from
(
select 'totalcount' as name,[LeeWhoee],[DePaul],[LeeWhoeeUniversity]
from
(
select name,count(*) as totalcount from testpivot
group by name
) a
pivot
(
max(totalcount) for name in ([LeeWhoee],[LeeWhoeeUniversity],[DePaul])
) b
) d
unpivot
(
_totalcount for _name in([LeeWhoee],[DePaul],[LeeWhoeeUniversity])
) c运行结果:
name totalcount
LeeWhoee 3
DePaul 2
LeeWhoeeUniversity 2
本文详细介绍了SQLSERVER中的PIVOT和UNPIVOT操作,包括基本概念、操作步骤及实例解析,帮助理解如何通过这些操作在数据表间进行数据转换。
1495

被折叠的 条评论
为什么被折叠?



