create table employee(empid int,empname varchar(20),salary int, month varchar(20));
select empid,sum(salary) as total from employee group by empid **where** total>25000;
Why can't we use where
in this program? Why is having key
the only accepted thing?
To simplify: WHERE
is used before a GROUP BY
clause to filter the rows. HAVING
is used after a GROUP BY
and can access the "result" of the GROUP BY
statement. See the documentation on the HAVING
statement in SELECT
statements :
The
HAVING
clause, like theWHERE
clause, specifies selection conditions. TheWHERE
clause specifies conditions on columns in the select list, but cannot refer to aggregate functions. TheHAVING
clause specifies conditions on groups, typically formed by theGROUP BY
clause. The query result includes only groups satisfying theHAVING
conditions. (If noGROUP BY
is present, all rows implicitly form a single aggregate group.)
That's why you can't access total
in your sum(salary) as total
expression with the WHERE
clause, but can access it with the HAVING
clause, which is applied after the result of sum(salary)
is calculated and the GROUP BY
clause is applied.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.