Sum and group by

If you have an Oracle database available, you should also have access to the hr test schema where are defined a few tables. Among them there is employees, that stores data that I'm about to use in this post.

We want to see how much is the salay costs for all the employees, grouped by the department they are working for.

This is a classical problem that could be solved easily using the SUM() function in conjunction with the GROUP BY clause in a SELECT statement.

We get the department id, the sum of all related employees salary and, to make this report more readable, we order it from the most wealthy department down to the poorest one:

select department_id, sum(salary)
from employees
GROUP BY department_id
order by sum(salary) desc;

If you want a fun introduction to SQL, consider reading Head First SQL. Actually, it uses MySQL, and not Oracle, as I'm doing currently. But this is not a big issue.

No comments:

Post a Comment