0

我的桌子:

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
4

2 回答 2

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

于 2013-02-28T12:20:47.797 回答
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);
于 2013-02-28T12:22:11.277 回答