May 2025
Intermediate to advanced
570 pages
7h 38m
Chinese
本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com
本章将介绍有助于创建报告的查询。这些查询通常涉及特定于报表的格式考虑以及不同级别的聚合。本章的另一个重点是转置或透视结果集:通过将行变成列来重塑数据。
一般来说,这些方法的共同点是允许你以不同于存储方式的格式或形状显示数据。随着你对透视功能的熟悉程度的提高,你无疑会发现它在本章介绍之外的用途。
您想从一组行中提取值,并将这些值转化为每组单行中的列。例如,您有一个显示各部门员工人数的结果集:
DEPTNO CNT
------ ----------
10 3
20 5
30 6
您希望重新格式化输出,使结果集如下:
DEPTNO_10 DEPTNO_20 DEPTNO_30
--------- ---------- ----------
3 5 6
这是一个典型的例子,说明数据的呈现形式与存储方式不同。
使用 CASE 和聚合函数 SUM 对结果集进行转置:
1 select sum(case when deptno=10 then 1 else 0 end) as deptno_10, 2 sum(case when deptno=20 then 1 else 0 end) as deptno_20, 3 sum(case when deptno=30 then 1 else 0 end) as deptno_30 4 from emp
这个示例是对透视的绝佳介绍。概念很简单:对于未使用透视查询返回的每一行,使用 CASE 表达式将行分隔成列。然后,由于这个特定问题是计算每个部门的员工人数,因此使用聚合函数 SUM 计算每个 DEPTNO 的出现次数。如果您难以理解具体的操作方法,请使用聚合函数 SUM 执行查询,并包含 DEPTNO 以提高可读性:
select deptno,case when deptno=10 then 1 else 0 end as deptno_10,case when deptno=20 then 1 else 0 end as deptno_20,case when deptno=30 then 1 else 0 end as deptno_30from emporder by 1DEPTNO DEPTNO_10 DEPTNO_20 DEPTNO_30 ------ ---------- ---------- ---------- 10 1 0 0 10 1 0 0 10 1 0 0 20 0 1 0 20 0 1 0 20 0 1 0 20 0 1 0 30 0 0 1 30 0 0 1 30 0 0 1 30 0 0 1 30 0 0 1 30 0 0 1
可以把每个 CASE 表达式看作是一个标志,用来确定某一行属于哪个 DEPTNO。此时,"行到列 "的转换已经完成;下一步是对 DEPTNO_10、DEPTNO_20 和 DEPTNO_30 返回的值进行简单求和,然后按 DEPTNO 进行分组。结果如下:
select deptno,sum(case when deptno=10 then 1 else 0 end) as deptno_10,sum(case when deptno=20 then 1 else 0 end) as deptno_20,sum(case when ...
Read now
Unlock full access