mysql compare columns in same table
I have a table in a mysql db as
id fruit number_eaten day
----------------------------------
1 apple 2 1
2 banana 1 1
3 orange 3 2
4 apple 1 开发者_如何学Go 2
5 banana 2 3
6 peach 1 3
I'm trying to figure out how to select such that I can compare how many was eaten per day and place into a spreadsheet so i get
fruit number_eaten_day_1 number_eaten_day_2 number_eaten_day_3
------------------------------------------------------------------------
apple 2 1 0
banana 1 0 2
orange 0 3 0
peach 0 0 1
it's easier to have separate row per fruit and day with summed value number_eaten:
select fruit, day, sum(number_eaten)
from fruits_eaten_by_day
group by fruit, day
but it should also be possible to have exact result you need by doing this:
select
fruit,
sum(if(day=1, number_eaten, 0)) as number_eaten_day_1,
sum(if(day=2, number_eaten, 0)) as number_eaten_day_2,
sum(if(day=3, number_eaten, 0)) as number_eaten_day_3
from fruits_eaten_by_day
group by fruit
精彩评论