2017-02-24 67 views
0

我想實現年度數據爲支點,這是我的查詢mysql表數據行

SELECT 
    month(te.topup_date) as month, 
    sum(CASE WHEN year(te.topup_date) = '2015' THEN te.topup_amount+ tp.topup_amount END) as '2015', 
    sum(CASE WHEN year(te.topup_date) = '2016' THEN te.topup_amount+ tp.topup_amount END) as '2016' 
from te_daily_topup as te 
inner join tp_daily_topup as tp on year(te.topup_date) = year(tp.topup_date) 
where year(te.topup_date) between '2015' and '2016' 
group by year(te.topup_date), month(te.topup_date) 

從上述查詢

month | 2015 | 2016 
-------------------- 
1  | 123 | 
2  | 2343 | 
1  |  |234 
2  |  |7667 

結果我期待結果對於低於:

month | 2015 | 2016 
-------------------- 
1  | 123 | 234 
2  | 2343 | 7667 

幫我修改這個查詢..

回答

2

單從GROUP BY刪除year()

select month(te.topup_date) as month, 
     sum(case when year(te.topup_date) = 2015 then te.topup_amount + tp.topup_amount end) as `2015`, 
     sum(case when year(te.topup_date) = 2016 then te.topup_amount + tp.topup_amount end) as `2016` 
from te_daily_topup te inner join 
    tp_daily_topup tp 
    on year(te.topup_date) = year(tp.topup_date) 
where year(te.topup_date) between 2015 and 2016 
group by month(te.topup_date); 

注意:不要爲整型常量,也爲列別名使用單引號。只對字符串和日期常量使用單引號。

+0

謝謝Gordon Linoff – madhan