获取平均值取决于月份?

时间:2013-02-28 11:58:11

标签: mysql

我的表:

rating   date
   4    12/02/2013
   3    12/02/2013
  2.5   12/01/2013
   3    12/01/2013
  4.5   21/11/2012
   5    10/11/2012

如果我在过去三个月(02,01,12)给出输入3,则应该得到评分结果的平均值

我尝试使用GROUP BY,但我得到了这个结果:

 rating   month
  3.5      02
 2.75      01

第12个月没有评级,所以没有输出.....

我想要的结果:

 rating   month
  3.5      02
 2.75      01
   0       12

2 个答案:

答案 0 :(得分:3)

问题是您想要返回不存在的月份。如果您没有包含日期​​的日历表,那么您将需要使用以下内容:

select d.mth Month,
  coalesce(avg(t.rating), 0) Rating
from 
(
  select 1 mth union all
  select 2 mth union all
  select 3 mth union all
  select 4 mth union all
  select 5 mth union all
  select 6 mth union all
  select 7 mth union all
  select 8 mth union all
  select 9 mth union all
  select 10 mth union all
  select 11 mth union all
  select 12 mth 
) d
left join yourtable t
  on d.mth = month(t.date)
where d.mth in (1, 2, 12)
group by d.mth

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

SELECT coalesce(avg(rating), 0.0) avg_rating, req_month
  FROM    yourTable
       RIGHT JOIN
          (SELECT month(now()) AS req_month
           UNION
           SELECT month(now() - INTERVAL 1 MONTH) AS req_month
           UNION
           SELECT month(now() - INTERVAL 2 MONTH) AS req_month) tmpView
       ON month(yourTable.date) = tmpView.req_month
 WHERE    yourTable.date > (  (curdate() - INTERVAL day(curdate()) - 1 DAY) - INTERVAL 2 MONTH)
  OR ratings.datetime IS NULL
GROUP BY month(yourTable.date);