2017-08-16 55 views
0

基於價值的「犧牲型」組MySql的總和不同類型從「犧牲」表費用爲這個職位更通用的標題是由員工

在同一臺MySql的總和不同列基於價值另一行,按又一排的

我的員工費用表:

id | employee_id | expense_cat_id | expense_amount | 
1 | 11   | 1    | 100   | 
2 | 11   | 1    | 200   | 
3 | 12   | 1    | 120   | 
4 | 12   | 1    | 140   | 
5 | 11   | 2    | 5    | 
6 | 12   | 2    | 8    |` 

,我想產生這樣的報告:

Employee Id | Expense Cat 1 Total Amount | Expense Cat 2 Total Amount 11 | 300 | 5 12 | 260 | 8

所以最初我以爲我可以用2名別名這樣的同桌:

SELECT employee_id, sum(expense_cat_1.expense_amount) as expense_1_total, sum(expense_cat_2.expense_amount) as expense_2_total FROM expenses as expense_cat_1 where expense_cat_1.expense_cat_id=1 , expenses as expense_cat_2 where expense_cat_2.expense_cat_id=2 group by employee_id

,但這是不正確的SQL語法,這對我來說很有意義。

所以我想我可以做兩employee表和費用表之間的連接上:

SELECT employees.id as employee_id, sum(expenses_cat_1.expense_amount) as expense_1_total, sum(expenses_cat_2.expense_amount) as expense_2_total FROM employees join expenses as expenses_cat_1 on employees.id = expenses_cat_1.employee_id and expenses_cat_1.expense_cat_id=1 join expenses as expenses_cat_2 on employees.id = expenses_cat_2.employee_id and expenses_cat_2.expense_cat_id=2 group by employees.id

其中接近,但其實是錯誤:

employee_id | expense_1_total | expense_2_total 11 | 300 | 10 12 | 260 | 16

爲代價總數是2倍!我認爲這是因爲加入對類別1的兩項費用中的每一項都顯示了兩行,並將它們相加。

我也嘗試了子查詢方法:

SELECT (SELECT sum(expense_amount) FROM expenses WHERE expense_cat_id = 1) AS sum1 , (SELECT sum(expense_amount) FROM expenses WHERE expense_cat_id = 2) AS sum2, employee_id FROM expenses group by employee_id

但這有同樣的問題作爲連接方法 - 貓2總數增加一倍。

如何讓第二次連接只包含費用_2總計一次?

我有個人不喜歡sql case語句,因爲他們看起來更像是一個過程式語言結構(而sql是聲明式的),但我很樂意考慮他們在這種情況下的使用 - 但我把挑戰放在了sql專家解決這個優雅。

+0

如果有兩個以上的貓?認真考慮處理應用程序代碼中的數據顯示問題 – Strawberry

回答

0

您正在尋找有條件聚集:

SELECT employee_id, 
     sum(case when expense_cat_id = 1 then expense_amount else 0 end) as expense_1_total, 
     sum(case when expense_cat_id = 2 then expense_amount else 0 end) as expense_2_total 
FROM expenses e 
GROUP BY employee_id;