这篇文章给大家分享的是“pivot函数是什么,具体用法是怎样的”,希望这篇文章对你一定的参考价值和帮助
提示:以下是本篇文章正文内容,下面案例仅供参考
在SQL中PIVOT函数又被称为行转列函数,该函数的作用就是将行转为列,使数据看起来更加直观明了
PIVOT 通过将表达式某一列中的唯一值转换为输出中的多个列来旋转表值表达式,并在必要时对最终输出中所需的任何其余列值执行聚合
SELECT <非透视的列>,
[第一个透视的列],
[第二个透视的列],
...
[最后一个透视的列]
FROM
表名
PIVOT
(
<聚合函数>(<要聚合的列>)
FOR
[<包含要成为列标题的值的列>]
IN ( [第一个透视的列], [第二个透视的列],
... [最后一个透视的列])
) AS <透视表的别名>
<可选的 ORDER BY 子句>;
pivot (聚合函数(要聚合的列) for <要旋转为行的列> in (目标列)) as 目标表名
if exists(select * from sys.databases where name='Student')
drop database Student
go
create database Student
go
use Student
create table students(
ID int not null,
Name varchar(50) not null,
Subject varchar(50) not null,
Grade int not null
)
insert into students values(1,'张三','语文',76)
insert into students values(1,'张三','数学',85)
insert into students values(1,'张三','英语',74)
insert into students values(2,'李四','语文',89)
insert into students values(2,'李四','数学',78)
insert into students values(2,'李四','英语',98)
select*from students
select Name as 姓名,[语文],[数学],[英语] from students PIVOT(sum(Grade)for [Subject] in([语文],[数学],[英语])) as p order by ID
关于SQL中行转列的方法还有很多,但是PIVOT函数能帮你节省很多的时间和代码,对此我觉得是比较好用的