2013-07-09 105 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