2013-02-28 102 views
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 

如果我给输入为3过去三个月(02,01,12),评级结果的平均值应该来

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

rating month 
    3.5  02 
2.75  01 

为12个月没有为当前没有输出.....

我想要的结果:

rating month 
    3.5  02 
2.75  01 
    0  12 
+0

不论多年来,他们(月)属于?和'21/11/2013'? – SparKot 2013-02-28 12:04:12

+0

对不起21/11/2012 – Kumar 2013-02-28 12:05:19

+0

你想要平均评分?然后平均(评级)在哪个月像''; – Parvathy 2013-02-28 12:06:14

回答

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

+0

我已更新我的问题看到它... – Kumar 2013-02-28 12:34:45

+0

需要得到最后三个月的价值通过给输入作为3 .... – Kumar 2013-02-28 12:40:28

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); 
+0

做了一些改变的问题看到它.... – Kumar 2013-02-28 12:36:49

+0

需要获得最后三个月的价值通过给输入3 .... – Kumar 2013-02-28 12:41:09