In the select statement, you can use the groupby clause to divide rows into smaller groups. Then, use the grouping function to return the summary information of each group. In addition, you can use the having clause to limit the returned result set. The group by clause can group query results and return the summary information of rows. Oracle groups query results by the value of the expression specified in the group by clause.
In a query statement with a groupby clause, the columns specified in the select list are either columns specified in the groupby clause or contain clustering functions.
Copy codeThe Code is as follows:
Selectmax (sal), jobempgroupbyjob;
(Note max (sal): the job does not necessarily appear, but it makes sense)
Select and groupby of the query statement. The having clause is the only place where the clustering function appears. In the where clause, clustering functions cannot be used.
Copy codeThe Code is as follows:
Selectdeptno, sum (sal) fromempwheresal> 1200 groupbydeptnohavingsum (sal)> 8500 orderbydeptno;
When the having clause is used in the gropuby clause, only groups meeting the having condition are returned in the query results. A SQL statement can contain the where clause and having clause. Having is similar to the where clause and is used to set conditions.
The where clause is used to remove rows that do not meet the where condition before grouping query results. That is, data is filtered before grouping. The condition cannot contain clustering functions, use the where condition to display specific rows.
The having clause is used to filter groups that meet the conditions. That is, data is filtered after the group. conditions often contain clustering functions and the having condition is used to display specific groups, you can also use multiple grouping standards for grouping.
Queries the number of employees for each position in each department
Copy codeThe Code is as follows:
Selectdeptno, job, count (*) fromempgroupbydeptno, job;
If you are still confused about when to use WHERE and when to use HAVING, follow the instructions below:
The WHERE statement is prior to the GROUPBY statement, and the SQL statement is calculated before the group.
HAVING statement after the GROUPBY statement; SQL calculates the HAVING statement after the group.