0
id | name | region_id
1 | sation1 | 1
2 | sation2 | 1
3 | sation3 | 2
4 | sation4 | 2
expenditure_heads
id | name
1 | exp1
2 | exp2
3 | exp3
4 | exp4
5 | exp5
expense_details
id | expenditure_head_id | station_id | year | month | expense
1 | 1 | 1 | 2015 | 1 | 300
2 | 2 | 1 | 2015 | 1 | 250
3 | 3 | 1 | 2015 | 1 | 100
4 | 4 | 1 | 2015 | 1 | 50
5 | 5 | 1 | 2015 | 1 | 200
6 | 1 | 3 | 2015 | 1 | 75
7 | 2 | 3 | 2015 | 1 | 15
8 | 3 | 3 | 2015 | 1 | 40
9 | 4 | 3 | 2015 | 1 | 300
10 | 5 | 3 | 2015 | 1 | 250
11 | 1 | 3 | 2015 | 2 | 100
12 | 2 | 3 | 2015 | 2 | 50
13 | 3 | 3 | 2015 | 2 | 200
14 | 4 | 3 | 2015 | 2 | 300
15 | 5 | 3 | 2015 | 2 | 250
我的願望的結果讓所有的站的年度報告與每個expenditure_heads的代價,我試圖
SELECT exp.name AS expenditure,st.name AS station,x.totalexpense
FROM expenditure_heads AS exp
LEFT JOIN
(SELECT expenditure_head_id,station_id,SUM(expense) as totalexpense
FROM expense_details
WHERE year = '2015'
GROUP by expenditure_head_id,station_id
)
AS x ON exp.id = x.expenditure_head_id
LEFT JOIN stations AS st ON x.station_id = st.id WHERE st.region_id=2
此只給出站的一個正確的結果,多數民衆贊成在expense_details
expenditure | station | totalexpense
exp1 | sation3 | 175
exp2 | sation3 | 65
exp3 | sation3 | 240
exp4 | sation3 | 600
exp5 | sation3 | 500
,但我想ID導致這樣的
expenditure | station | totalexpense
exp1 | sation3 | 175
exp2 | sation3 | 65
exp3 | sation3 | 240
exp4 | sation3 | 600
exp5 | sation3 | 500
exp1 | sation4 | 0
exp2 | sation4 | 0
exp3 | sation4 | 0
exp4 | sation4 | 0
exp5 | sation4 | 0
預先感謝您
其不與左外工作的加盟也 – sanu
我已編輯答案與第二種查詢方式。你能檢查它是否有效嗎? –
不起作用可能會在查詢中出錯 – sanu