0

我在 mysql 数据库中有一个表

id  fruit   number_eaten   day   
----------------------------------
1  apple        2           1
2  banana       1           1
3  orange       3           2
4  apple        1           2
5  banana       2           3
6  peach        1           3

我试图弄清楚如何选择这样我可以比较每天吃多少并放入电子表格中,所以我得到

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
4

1 回答 1

1

使用总和值 number_eaten 更容易地为每个水果和一天单独设置一行:

select fruit, day, sum(number_eaten)
from fruits_eaten_by_day 
group by fruit, day

但也应该可以通过这样做得到你需要的准确结果:

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
于 2011-07-19T22:49:42.227 回答