oracle sql 选择语法与 GROUP BY 和 HAVING 子句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20188862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 02:06:30  来源:igfitidea点击:

oracle sql select syntax with GROUP BY and HAVING clause

sqloraclegroup-byhaving

提问by user2081775

I been going thru some of the sql syntax to study for the oracle sql exam, I found something rather confusing

我一直在通过一些 sql 语法来学习 oracle sql 考试,我发现有些东西相当混乱

based on the officialreferences, the select syntax is as follow :

根据官方参考,选择语法如下:

SELECT
    [ hint ]
    [ { { DISTINCT | UNIQUE } | ALL } ]
   select_list
     FROM { table_reference | join_clause | ( join_clause ) }
            [ , { table_reference | join_clause | (join_clause) } ] ...
     [ where_clause ]
     [ hierarchical_query_clause ]
     [ group_by_clause ]
     [ HAVING condition ]
     [ model_clause ]

based on this you cannot have the HAVING clause before the GROUP BY clause . However if i were to execute the following sql in the test server :

基于此,您不能在 GROUP BY 子句之前使用 HAVING 子句。但是,如果我要在测试服务器中执行以下 sql:

select 
   department_id , count (*)      
from 
    employees 
having 
    count(*) > 6 
group by 
    department_id ; 

it does not produce a syntax error , can some one help explain this ? I don't like to think that the reference docs is wrong , but if so I need some confirmation.

它不会产生语法错误,有人可以帮忙解释一下吗?我不喜欢认为参考文档是错误的,但如果是这样,我需要一些确认。

采纳答案by Armunin

As stated here:

如前所述这里

Use the HAVING clause to restrict the groups of returned rows to those groups for which the specified condition is TRUE. If you omit this clause, then the database returns summary rows for all groups.

Specify GROUP BY and HAVING after the where_clause and hierarchical_query_clause. If you specify both GROUP BY and HAVING, then they can appear in either order.

使用 HAVING 子句将返回的行组限制为指定条件为 TRUE 的那些组。如果省略此子句,则数据库将返回所有组的汇总行。

在 where_clause 和 hierarchy_query_clause 之后指定 GROUP BY 和 HAVING。如果您同时指定 GROUP BY 和 HAVING,则它们可以按任一顺序出现。