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

以学生表举个例子,展现学生的各门学科和成绩,我们先新建一张表(表中插入测试值的时候用到了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行数,顾名思义,一个是“行转列”另一个就是“列转行”,好了,这个函数的使用方法我会在下一篇介绍~~

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值