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) を 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 FiddlewithDemoを参照してください

于 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 に答える