I have a Invoice table with these columns.,
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
and I want to get USA total amount, NON USA total amount group by month, i am using these query i get only USA total amount
SELECT MONTH(date),YEAR(date),SUM(total) as usa_amount
FROM Invoice
WHERE YEAR(date) = '2016'
AND country='USA'
GROUP BY MONTH(date)
and i am getting this result
MONTH(date) YEAR(date) usa_amount
01 2016 100
02 2016 130
I want to this result using mysql unions or anything?
MONTH(date) YEAR(date) usa_amount non_usa_amount
01 2016 100 110
02 2016 130 130
Use a case
in the 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.