我有三个表:tbl_job1,tbl_job2和tbl_users。
tbl_job1:
ID| DataComplited | Profit | UserID |
===================================
1 | 2017-01-01 | 100 | 1 |
2 | 2017-02-01 | 200 | 1 |
3 | 2017-03-01 | 150 | 1 |
4 | 2017-01-01 | 400 | 2 |
5 | 2017-01-01 | 120 | 1 |
6 | 2017-02-03 | 30 | 1 |
tbl_job2:
ID| DataComplited | Profit | UserID |
===================================
1 | 2017-02-01 | 50 | 1 |
2 | 2017-03-01 | 20 | 1 |
3 | 2017-02-03 | 20 | 1 |
4 | 2017-02-03 | 50 | 1 |
tbl_users:
ID| fullname |
==============
1 | Robert |
2 | Maria |
我想看看:
Fullname | Year | Month | Profit 1 | Profit 2 | Total |
==========================================================
Maria | 2017 |January | 400.00 | |400.00 |
Robert | 2017 |January | 220.00 | |220.00 |
| |February| 230.00 | 120.00 |350.00 |
| | March | 150.00 | 20.00 |170.00 |
但我明白了:
Fullname | Year | Month | Profit 1 | Profit 2 | Total |
==========================================================
Maria |2017 |January | 400.00 | |400.00 |
Robert |2017 |January | 220.00 | |220.00 |
| |February| 260.00 | 120.00 |380.00 |
| | March | 150.00 | 20.00 |170.00 |
请看看罗伯特二月份的情况。 抱歉我的英语,我是俄语。但我认为你可以看到那些桌子上的所有东西。实际上我想每月看两个工作的总和。
我是MySql的新手,我尝试了这段代码:
SELECT
year(tbl_job1.DataComplited) AS `Year`,
DATE_FORMAT(tbl_job1.DataComplited, '%M') AS `Month`,
DATE_FORMAT(tbl_job1.DataComplited, '%m') AS Month_ord,
tbl_users.fullname,
SUM(tbl_job1.Profit) AS Profit_1
SUM(tbl_job2.Profit) AS Profit_2 ,
(SUM(tbl_job1.profit)) + (SUM(COALESCE(tbl_job2.profit, 0))) AS Total
FROM tbl_job1
LEFT OUTER JOIN tbl_job2 ON tbl_job1.DataComplited = tbl_job2.DataComplited
INNER JOIN tbl_users ON tbl_job1.UserID = tbl_users.ID
GROUP BY tbl_users.fullname,
month(tbl_job1.DataComplited),
DATE_FORMAT(`month`, '%m'),year
ORDER BY tbl_users.fullname,
year(tbl_job1.DataComplited),
DATE_FORMAT(tbl_job1.DataComplited, '%M')
请帮帮我。
谢谢,我,但我决定自己。
SELECT
year(a.DataComplited) AS `Year`,
DATE_FORMAT(a.DataComplited, '%M') AS `Month`,
tbl_users.fullname,
SUM(a.Profit) AS Profit_1,
b.Profit AS Profit_2,
SUM(COALESCE(a.Profit, 0)) + COALESCE(b.Profit, 0) as Total
FROM tbl_job1 as a
INNER JOIN tbl_users ON a.UserID = tbl_users.ID
LEFT OUTER JOIN
(
SELECT
DATE_FORMAT(DataComplited, '%M') AS `Month`,
DataComplited,
SUM(COALESCE(tbl_job2.profit, 0)) AS Profit
FROM tbl_job2
GROUP BY month(DataComplited), DATE_FORMAT(`month`, '%m')
) AS b USING (DataComplited)
GROUP BY tbl_users.fullname, month(a.DataComplited), DATE_FORMAT(`month`, '%m'), year
ORDER BY tbl_users.fullname, year(a.DataComplited), DATE_FORMAT(a.DataComplited, '%m')