本文中介绍的SQL中行列转换和嵌套式侧栏的生成,将SQL
语句查询的结果转换成我们想要的结果。
- 行转列,制作交叉表头
- 列转行
![3faac4497fdcb451cee69e043ccf0ce2.png](https://img-blog.csdnimg.cn/img_convert/3faac4497fdcb451cee69e043ccf0ce2.png)
实现行列转换(行—>列):制作交叉表
需求
根据下面的表Courses
制作员工和课程的交叉表
![ec526a209b33d0a6706d680b6c5d661d.png](https://img-blog.csdnimg.cn/img_convert/ec526a209b33d0a6706d680b6c5d661d.png)
生成如下的交叉表:
![49df49ef7fd88ef860cfb184941686dc.png](https://img-blog.csdnimg.cn/img_convert/49df49ef7fd88ef860cfb184941686dc.png)
方法-外连接实现
-- 水平展开求交叉表,使用外连接
select C0.name,
case when C1.name is not null then 'o' else null end as "SQL入门", -- 如果某位员工学习过某课程,则课程的相应列则出现他的名字,否则为NULL
case when C2.name is not null then 'o' else null end as "UNIX基础",
case when C3.name is not null then 'o' else null end as "java中级"
from (select distinct name from Courses) C0 -- C0是侧栏
left outer join(select name from Courses where course='SQL入门') C1 on C0.name = C1.name -- select子句中的查询结果标为C1
left outer join(select name from Courses where course='UNIX基础') C2 on CO.name = C2.name
left outer join(select name from Courses where course='java中级') C3 on CO.name = C3.name;
SQL中指定了名称的表和视图都是相当于是集合
C0-C3
的各自内容如下:
- C0包含了全部的员工
- C1-C3每个课程学习者的集合<