mysql比较同一个表中的列

时间:2011-07-19 22:44:56

标签: mysql join union self-join

我在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

1 个答案:

答案 0 :(得分: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