2013-07-09 70 views
2

我有那些有很多销售和属于部门的工人。我希望看到一个部门每天有多少销售额。postgresql集合的总和(总和)

为了简单起见,让我们假设一个工人只属于一个部门。

例子:

部门:

| 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 

如何把这些资金(总额人均出售)并按部门汇总?

+0

为什么有'department_employees'表?员工表中不应该有'department_id'列吗? – Bohemian

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

完美,谢谢!此外,刚刚从澳大利亚回来,在动物园看到一对夫妇的袋熊。最好使用我在一段时间看过的个人资料图片。 –

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