---------行转列
--建表
create table test(编号 int,姓名 varchar(20),季度 int,销售额 int)
insert into test values(1,'simon',1,1000)
insert into test values(1,'simon',2,2000)
insert into test values(1,'simon',3,3000)
insert into test values(1,'simon',4,4000)
insert into test values(2,'meme',1,5000)
insert into test values(2,'meme',2,6000)
insert into test values(2,'meme',3,7000)
insert into test values(2,'meme',4,8000)
--执行普通查询
select * from test
--执行转换查询
select 编号,姓名,
[1] as "一季度",
[2] as "二季度",
[3] as "三季度",
[4] as "四季度",
[5] as "随便1"
from
test
pivot
(
sum(销售额)
for 季度 in
([1],[2],[3],[4],[5])
)
as pvt
--------列转行
--建表
create table test2(编号 int,姓名 varchar(20), 一季度 int, 二季度 int, 三季度 int, 四季度 int)
insert into test2 values(1,'simon',1000,2000,4000,5000)
insert into test2 values(2,'meme',3000,3500,4200,5500)
--执行普通查询
select * from test2
--执行转换查询
select 编号,姓名,季度,销售额
from
test2
unpivot
(
销售额
for 季度 in
(一季度,二季度,三季度,四季度)
)
as unpvt
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/16436858/viewspace-679376/ ,如需转载,请注明出处,否则将追究法律责任。