AVG限制为每组的最后3个值

时间:2017-01-29 20:01:43

标签: mysql

基本上我有两张桌子:

这里有代码创建两个表,如果这可以帮助那些愿意帮助我的人:

CREATE TABLE IF NOT EXISTS `coefficients` ( 
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `datetime` datetime NOT NULL,
    `campaign_id` int(11) NOT NULL,  
    `score` decimal(10,2) NOT NULL,  
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

INSERT INTO `coefficients` (`id`, `datetime`, `campaign_id`, `score`) VALUES    
    (1, '2017-01-29 22:32:13', 1, 20.00),   
    (2, '2017-01-29 22:36:22', 1, 34.00),   
    (3, '2017-01-29 22:36:30', 1, 30.00),   
    (4, '2017-01-29 22:36:43', 1, 1000.00), 
    (5, '2017-01-29 22:37:13', 2, 10.00),   
    (6, '2017-01-29 22:37:26', 2, 15.00),   
    (7, '2017-01-29 22:37:43', 2, 20.00),   
    (8, '2017-01-29 22:30:51', 2, 1000.00);

CREATE TABLE IF NOT EXISTS `statistics` ( 
    `id` int(11) NOT NULL AUTO_INCREMENT,  
    `campaign_id` int(11) NOT NULL,  
    `stats1` int(11) NOT NULL,  
    `stats2` int(11) NOT NULL,  
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

INSERT INTO `statistics` (`id`, `campaign_id`, `stats1`, `stats2`) VALUES   
    (1, 1, 34, 38),
    (2, 2, 23, 45);

我想根据每个campaign_id的最新3个记录系数计算每个campaign_id的平均系数。

这里有两张桌子的截图和我需要得到的结果:

data + result (visual representation)

主要的问题是,如果我只需要基于3个最新记录的nu,bers的每个campaign_id的平均系数,我不知道如何加入这两个表:(

我将不胜感激任何帮助

2 个答案:

答案 0 :(得分:0)

在MySQL中,最好的方法通常是使用变量。获取统计信息只是join,所以这并不重要。让我们从coefficients表中获得平均值:

select c.campaign_id, avg(c.score) as avg_score
from (select c.*,
             (@rn := if(@c = c.campaign_id, @rn + 1,
                        if(@c := c.campaign_id, 1, 1)
                       )
             ) as rn
      from coefficients c cross join
           (select @rn := 0, @c := -1) params
      order by c.campaign_id, c.datetime desc
     ) c
where rn <= 3
group by c.campaign_id;

答案 1 :(得分:0)

以下查询将为campaign_id表中的coefficients提供前3条记录:

SET @currcount = NULL, @currvalue = NULL;
SELECT id, campaign_id, score, c_index FROM (
  SELECT
  id, campaign_id, score, 
  @currcount := IF(@currvalue = campaign_id, @currcount + 1, 1) AS c_index,
  @currvalue := campaign_id AS s
  FROM coefficients
  order by id
) AS a where c_index <= 3

现在,您只需要为此查询添加GROUP BY,计算average分数并将其与statistics表格结合起来,例如:

SET @currcount = NULL, @currvalue = NULL;
SELECT a.id, a.campaign_id, avg(score), c_index, s.stats1, s.stats2 FROM (
  SELECT
  id, campaign_id, score, 
  @currcount := IF(@currvalue = campaign_id, @currcount + 1, 1) AS c_index,
  @currvalue := campaign_id AS s
  FROM coefficients
  order by id
) AS a join statistics s on a.campaign_id = s.campaign_id
where c_index <= 3
group by campaign_id

这是 SQL Fiddle