I've got workers who have many sales and who belong to departments. I'd like to see how many sales a department is making per day.
For simplicity, let's say a worker belongs to only one department.
Example:
departments:
| id | name |
| 1 | Men's Fashion |
| 2 | Women's Fashion |
workers:
| id | name |
| 1 | Timmy |
| 2 | Sally |
| 3 | Johnny |
sales:
| id | worker_id | datetime | amount |
| 1 | 1 | 2013-1-1 08:00:00 | 1 |
| 2 | 1 | 2013-1-1 09:00:00 | 3 |
| 3 | 3 | 2013-1-2 08:00:00 | 8 |
department_employees
| id | worker_id | department_id |
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 3 | 2 |
I'd like to get
| department | amount |
| Men's Fashion | 4 |
| Women's Fashion | 8 |
To get the individual worker's total sales, I can do
SELECT worker_id, SUM(amount) FROM sales
GROUP BY worker_id
How do I take those sums (the total amount sold per worker) and aggregate it by department?