postgresql聚合总和(总和)

时间:2013-07-09 14:50:16

标签: sql postgresql select join aggregate-functions

我的工作人员有很多销售人员,属于部门。我想知道一个部门每天的销售额是多少。

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

示例:

部门:

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

department_employees

| 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

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

2 个答案:

答案 0 :(得分:3)

不要求和,而是通过department_employees表从销售加入部门:

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

答案 1 :(得分: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