Aggregated data can be filtered in two ways to allow you complete flexibility within SELECT statements:
The WHERE clause was reviewed in Chapter 44, "Basic SQL." The following example returns the number of employees in each department, including only employees residing in the specified country: SELECT department_name, COUNT(*) AS num_employees FROM employees, departments WHERE employees.department_id=departments.department_id AND employees.country='USA' GROUP BY department_name ORDER BY department_name This next example returns the number of employees in each department that has 100 or more employees: SELECT department_name, COUNT(*) AS num_employees FROM employees, departments WHERE employees.department_id=departments.department_id GROUP BY department_name HAVING COUNT(*) >= 100 ORDER BY department_name NOTE You can use both WHERE and HAVING in the same SELECT statement if necessary. WHERE must always be the first clause after the tables (specified in the FROM clause). |