SELECT sum(salary) AS amount
FROM employees
GROUP BY department
WHERE amount > 500000;
The idea with this query is to find departments at a given company where the total salary expenditure is greater than $500,000. However, it won't work because the 'amount' field is a calculated value and cannot be used by the WHERE clause. You'll get an error like this: Unknown column 'amount' in 'where clause'. The correct way to write this query is by using HAVING as follows:
SELECT sum(salary) AS amount
FROM employees
GROUP BY department
HAVING amount > 500000;
This time, MySQL will calculate all the 'amount' values then use the HAVING clause to filter out any records where the amount is <= 500000.
Here we use WHERE and HAVING in combination:
SELECT sum(salary) AS amount
FROM employees
WHERE salary < 50000
GROUP BY department
HAVING amount > 500000;
In this query we find departments at a given company where the total salary expenditure is greater than $500,000 but only including employees who make less than $50,000 a year.
No comments:
Post a Comment