您的位置:首页 > 数据库

浅谈SQLServer行列转换PIVOT函数的使用

2017-08-04 13:54 148 查看
以学生表举个例子,展现学生的各门学科和成绩,我们先新建一张表(表中插入测试值的时候用到了rand取随机数,没用过的可以了解下-->点击打开):
Create Table Students(Name varchar(10), Subject Nvarchar(10),Score int)
Insert into Students
Select 'Andy' ,'Chiness',round(60+40*rand(),0) Union all
Select 'Burgess' ,'Chiness',round(60+40*rand(),0) Union all
Select 'Ula' ,'Chiness',round(60+40*rand(),0) Union all
Select 'Lily' ,'Chiness',round(60+40*rand(),0) Union all
Select 'Demon' ,'Chiness',round(60+40*rand(),0) Union all
Select 'Andy' ,'Math',round(60+40*rand(),0) Union all
Select 'Burgess' ,'Math',round(60+40*rand(),0) Union all
Select 'Ula' ,'Math',round(60+40*rand(),0) Union all
Select 'Lily' ,'Math',round(60+40*rand(),0) Union all
Select 'Demon' ,'Math',round(60+40*rand(),0) Union all
Select 'Andy' ,'English',round(60+40*rand(),0) Union all
Select 'Burgess' ,'English',round(60+40*rand(),0) Union all
Select 'Ula' ,'English',round(60+40*rand(),0) Union all
Select 'Lily' ,'English',round(60+40*rand(),0) Union all
Select 'Demon' ,'English',round(60+40*rand(),0)

这张表的呈现形式如下:



通过行列转换函数:
SELECT * FROM Students
PIVOT(MAX(SCORE) FOR Subject IN(Chiness,Math,English) ) AS PVT

这边需要留意一下PIVOT函数使用的结构了,首先是写一个查询语句,然后是对这个查询结果集中的某一列的值进行了行列转换的操作(我这里是把学科这一列的值“语文、数学、英语”转换为列),其中还必须包含了一个聚集函数(聚集函数一共有5个,分别是:count、sum、max、min、avg,无论是用哪一个聚集函数都代表着不同的意义,我这里用的MAX,针对这里聚集函数的使用我在后面的篇章中有讲到-->点击打开
呈现形式如下:



注:pivot函数前面接的一定是一条查询语句,我上面的这条例子查询语句比较简单,直接select * from 也就通过了,最终结果也没有报错,其实正规来讲,如果select 语句比较复杂,这种写法可能会报错的,下面有一种保险一点的写法:
SELECT * FROM (
--这里写复杂的sql查询语句
) a
PIVOT(--此次省略相关code) AS PVT
之前的例子可以这样写:
SELECT * FROM (
SELECT * FROM Students
) a
PIVOT(MAX(SCORE) FOR Subject IN(Chiness,Math,English) ) AS PVT
最终的执行结果是一样的!

和PIVOT相反的还有一个UNPIVOT行数,顾名思义,一个是“行转列”另一个就是“列转行”,好了,这个函数的使用方法我会在下一篇介绍~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: