2017-05-27 122 views
-4

我有2個表 ,我想要結果作爲此使用聯接查詢。我沒有任何想法 Join Query ByMysql加入聯盟查詢按日期

TBL_SUCCESS_ORDER 
------------------------ 
id | date | amount 
------------------------- 
1 | 2017-01-01 | 1000 
2 | 2017-01-06 | 300 
3 | 2017-01-29 | 50 
4 | 2017-02-02 | 100 
5 | 2017-02-16 | 400 
6 | 2017-03-01 | 500 
7 | 2017-04-03 | 1200 



TBL_FAIL_ORDER 
------------------------ 
id | date | amount 
------------------------- 
1 | 2017-01-03 | 400 
2 | 2017-01-07 | 300 
3 | 2017-01-24 | 50 
4 | 2017-02-02 | 100 
5 | 2017-04-07 | 200 


RESULT 
------------------------------------------------------------------ 
year | month | sum_of_succes_amount | sum_of_fail_amount | total 
------------------------------------------------------------------ 
2017 | January |     1350 |    750 | 2100 
2017 | Febuary |     500 |    100 | 600 
2017 | March |     500 |     0 | 500 
2017 | April |     1200 |    200 | 1400 

我一直堆了整整一個星期我沒有得到它。當我連接api json

TBL_PENDING_ORDER 
------------------------ 
id | date | amount 
------------------------- 
1 | 2017-04-03 | 600 
2 | 2017-05-07 | 600 

RESULT 
----------------------------------------------------------------------------------------- 
year | month | sum_of_succes_amount | sum_of_fail_amount | sum_of_pending_amount |total 
----------------------------------------------------------------------------------------- 
2017 | January |     1350 |    750 |      0 | 2100 
2017 | Febuary |     500 |    100 |      0 | 600 
2017 | March |     500 |     0 |      0 | 500 
2017 | April |     1200 |    200 |     600 | 2000 
2017 |  May |     0 |     0 |     600 | 600 

如果我添加第三個表? TBL_PENDING_ORDER

+0

見https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-非常簡單的SQL查詢 – Strawberry

+3

然後等等等等等 – Strawberry

回答

0

您可以使用使用UNION ALLGROUP BY以下解決方案:

SELECT 
    YEAR(x.date), 
    MONTH(x.date), 
    SUM(CASE WHEN x.type = 'S' THEN amount ELSE 0 END) AS sum_of_succes_amount, 
    SUM(CASE WHEN x.type = 'F' THEN amount ELSE 0 END) AS sum_of_fail_amount, 
    SUM(amount) AS total 
FROM (
    SELECT id, date, amount, 'S' AS type FROM TBL_SUCCESS_ORDER 
    UNION ALL 
    SELECT id, date, amount, 'F' AS type FROM TBL_FAIL_ORDER 
)x GROUP BY YEAR(x.date), MONTH(x.date) 

您要添加第三個表TBL_PENDING_ORDER

SELECT 
    YEAR(x.date), 
    MONTH(x.date), 
    SUM(CASE WHEN x.type = 'S' THEN amount ELSE 0 END) AS sum_of_succes_amount, 
    SUM(CASE WHEN x.type = 'F' THEN amount ELSE 0 END) AS sum_of_fail_amount, 
    SUM(CASE WHEN x.type = 'P' THEN amount ELSE 0 END) AS sum_of_pending_amount, 
    SUM(amount) AS total 
FROM (
    SELECT id, date, amount, 'S' AS type FROM TBL_SUCCESS_ORDER 
    UNION ALL 
    SELECT id, date, amount, 'F' AS type FROM TBL_FAIL_ORDER 
    UNION ALL 
    SELECT id, date, amount, 'P' AS type FROM TBL_PENDING_ORDER 
)x GROUP BY YEAR(x.date), MONTH(x.date) 
+0

如此不錯,你救了我的一天...如果添加第三個表,這是TBL_PENDING_ORDER其相同格式的兩個表... –

+0

爲什麼downvote?我不喜歡沒有理由的低估... –

+0

也許他們不明白... –