Here is my query that only runs correctly when using the restrictive condition in the WHERE before the Group By and not when using the restrictive condition in the Having after the Group By. I thought that the Having acts like the Where clause and should be used when there is a need to do a Group By but this query below is not following that logic:
/* Calculate the total actual costs for all projects not over-budgeted for any manager. Display the manager's name, project, and sums for their individual projects.
Select mg_name, p_name, sum(actual_cost), sum(expected_cost)
From Project join manager on p_manager = mg_number
Where actual_cost <= expected_cost
Group by mg_name;
Incorrect query below that gives an error in MySQL noting that the actual_cost is not known in the Having (Error Code: 1054. Unknown column 'actual_cost' in 'having clause')
Select mg_name, p_name, sum(actual_cost), sum(expected_cost)
From Project join manager on p_manager = mg_number
Group by mg_name
Having actual_cost <= expected_cost;
Can someone explain why the first query works and the second does not?