2

我有很多销售人员,他们属于部门。我想看看一个部门每天的销售额。

为简单起见,假设一名工人只属于一个部门。

例子:

部门:

| id | name            |
| 1  | Men's Fashion   |
| 2  | Women's Fashion |

工作人员:

| id  | name   |
| 1   | Timmy  |
| 2   | Sally  |
| 3   | Johnny |

销售量:

| 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     |

部门_员工

| id | worker_id | department_id |
| 1  |   1       |    1          |
| 2  |   2       |    1          |
| 3  |   3       |    2          |

我想得到

|  department     | amount |
| Men's Fashion   | 4      |
| Women's Fashion | 8      |

要获得单个工人的总销售额,我可以

SELECT worker_id, SUM(amount) FROM sales
GROUP BY worker_id

我如何获取这些总和(每个工人的总销售额)并按部门汇总?

4

2 回答 2

3

不要求和,而是通过 Department_employees 表从 sales 加入到部门:

select d.name, sum(s.amount)
from sales s
join department_employees de on de.worker_id = s.worker_id
join departments d on d.id = de.department_id
group by d.name
于 2013-07-09T14:54:13.807 回答
1

聚合函数和分组也可以在一个带有关节的语句中工作。

尝试类似:

SELECT name, SUM(amount) FROM departments, department_employees, sales
WHERE departments.id = department_employees.department_id 
AND sales.worker_id = department_employees.worker_id
GROUP BY name
于 2013-07-09T15:00:37.507 回答