大家好,這里是架構資源棧!點擊上方關注,添加“星標”,一起學習大廠前沿架構!
從 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_MB2 FROM dba_segments3 GROUP BY Malek4 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_MBFROM dba_segmentsGROUP 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_MB2 FROM dba_segments3 GROUP BY Malek4 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_MBFROM dba_segmentsGROUP 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_MBFROM dba_segmentsGROUP 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