我有一个要求,我需要在所有经销商的月份范围内选择平均记录。但这里的条件是,如果一个经销商没有特定月份的记录,那么应该选择他的最新记录并添加到当月。
要求是: 选择3月到7月之间所有经销商的平均值。
我写的条件只取一个月的所有经销商的平均值,并不考虑最佳输入记录。请让我知道我能在这做什么。
我的SQL:
select avg(dealer_score), month(end_time) as month from dealers where end_time>='2015-03-01' and end_time <= '2015-07-01 23:59:59' group by month(end_time)
当前输出
dealer_score | month
30 | March
90| July
期望输出
dealer_score | month
30% | March
30% | April
30% | May
30% | June
90% | July
经销商表中的记录
dealer_id| dealer_name| dealer_score| end_time
1| abc| 30| '2015-03-01 20:00:00 00:00:00'
2| xyz| 30| '2015-03-01 21:00:00 00:00:00'
3| ABC| 90| '2015-07-01 23:00:00 00:00:00'
4| XYZ| 90| '2015-07-01 23:15:00 00:00:00'
答案 0 :(得分:0)
如果您只想延长所有五个月的记录,您可以执行以下操作:
select mon.mon,
(if(@a2 := @a,
if(@a := coalesce(avgds, @a), @a2, @a2), avgds)
) as avgds
from (select 3 as mon union all select 4 union all select 5 union all
select 6 union all select 7
) mon left join
(select month(end_time) as mon, avg(dealer_score) as avgds
from dealer
group by month(end_time)
) d
on d.mon = m.mon cross join
(select @a := 0) params
order by mon;