2016-08-04 48 views
1

我有這些列的發票表,如何在使用MySQL的單個查詢中運行兩個不同的查詢?

id total date   country 
1 50 2016-01-25 USA 
2 40 2016-01-24 UK 
3 30 2016-01-22 France 
4 40 2016-01-26 UK 
5 50 2016-01-18 USA 
6 60 2016-02-20 USA 
7 70 2016-02-21 USA 
8 55 2016-02-18 UK 
9 75 2016-02-19 France 

,我希望得到美國的總量,按月份非美國總量組,我使用這些查詢我得到的只有美國總量

SELECT MONTH(date),YEAR(date),SUM(total) as usa_amount 
FROM Invoice 
WHERE YEAR(date) = '2016' 
    AND country='USA' 
GROUP BY MONTH(date) 

和我得到這個結果

MONTH(date) YEAR(date) usa_amount 
01   2016   100 
02   2016   130 

我想用mysql工會或任何這樣的結果?

MONTH(date) YEAR(date) usa_amount non_usa_amount 
01   2016   100  110 
02   2016   130  130 

回答

0

使用在sum()

SELECT MONTH(date), 
     SUM(case when country = 'USA' then total else 0 end) as usa_amount, 
     SUM(case when country <> 'USA' then total else 0 end) as non_usa_amount 
FROM Invoice 
WHERE YEAR(date) = 2016 
GROUP BY MONTH(date) 
+0

我想case到非美國量也隨着相同的查詢? –

+0

是的,試試吧。它將工作 –

+0

thx很多juergen,這個答案正是我想要的是, –

相關問題