强啊!Oracle Database 23aiOracle Database 23ai:使用列别名进行分组排序!

发布于:2025-05-07 ⋅ 阅读:(9) ⋅ 点赞:(0)

大家好,这里是架构资源栈!点击上方关注,添加“星标”,一起学习大厂前沿架构!

从 Oracle Database 23ai 开始,您可以在 GROUP BY 和 HAVING 子句中直接使用列别名。此功能在早期版本的 Oracle Database 中不可用。

Oracle 21c 中的示例:

在 Oracle 21c 中,尝试在 GROUP BY 或 HAVING 子句中使用列别名将导致错误:

Oracle Database 21c Enterprise Edition Release 21.0.0.0.0 - Production
SQL> SELECT LOWER(owner) AS Malek, SUM(bytes / 1024 / 1024) AS SIZE_MB
  2    FROM dba_segments
  3   GROUP BY Malek
  4  HAVING SIZE_MB > 100;
ERROR at line 4:
ORA-00904: "SIZE_MB": invalid identifier

Enter fullscreen mode Exit fullscreen mode

为了避免 Oracle 21c 中的无效标识符错误,您必须重写查询,而不使用 GROUP BY 和 HAVING 子句中的别名:

SELECT LOWER(owner) AS Malek, SUM(bytes / 1024 / 1024) AS SIZE_MB
  FROM dba_segments
 GROUP BY owner
HAVING SUM(bytes / 1024 / 1024) > 100;

Enter fullscreen mode Exit fullscreen mode

Oracle 23ai 中的示例:

在 Oracle 23ai 中,上述两个查询均有效,现在可以在 HAVING 子句中直接使用别名 SIZE_MB:

Connected to Oracle Database 23ai Free, Release 23.0.0.0.0 
SQL> SELECT LOWER(owner) AS Malek, SUM(bytes / 1024 / 1024) AS SIZE_MB
  2         FROM dba_segments
  3        GROUP BY Malek
  4       HAVING SIZE_MB > 100;

MALEK      SIZE_MB
------ ----------
sys         672

Enter fullscreen mode Exit fullscreen mode

Oracle 23ai 中的其他增强功能:

Oracle 23ai 还引入了在 GROUP BY 子句中使用列位置的功能。要启用此功能,需要将 group_by_position_enabled 参数设置为 TRUE。具体工作原理如下:

SQL> SELECT LOWER(owner) AS Malek, SUM(bytes / 1024 / 1024) AS SIZE_MB
  FROM dba_segments
 GROUP BY 1
HAVING SIZE_MB > 100;

ERROR at line 1:
ORA-00979: "OWNER": must appear in the GROUP BY clause or be used in an aggregate function

Enter fullscreen mode Exit fullscreen mode

启用 group_by_position_enabled 参数后:

SQL> ALTER SESSION SET group_by_position_enabled = TRUE;
Session altered.

SQL> SELECT LOWER(owner) AS Malek, SUM(bytes / 1024 / 1024) AS SIZE_MB
  FROM dba_segments
 GROUP BY 1
HAVING SIZE_MB > 100;

MALEK      SIZE_MB
------ ----------
sys         672

Enter fullscreen mode Exit fullscreen mode

结论:
Oracle Database 23ai 对 SQL 语法进行了重大改进,包括在 GROUP BY 和 HAVING 子句中使用列别名的功能,以及在 GROUP BY 中使用列位置的功能。这些增强功能简化了查询编写并提高了可读性。

如果这篇文章对你有帮助的话,别忘了【在看】【点赞】支持下哦~

原文地址:https://mp.weixin.qq.com/s/aZ0_Df47isqVRAyAG_dzrg


网站公告

今日签到

点亮在社区的每一天
去签到