如何平均最近5笔交易的最后金额

时间:2015-01-08 02:25:57

标签: mysql limit

我有两个交易表和一个产品表。产品表有一个名为" product"的列。事务表有一个名为" amount"的列。我想获得每种产品的最后5笔交易的平均值。到目前为止我有这个,但不能找出一个声明,使它只抓住每个不同产品的最后5个:

SELECT avg(amount) as price, p.product_name, p.producer
FROM wp_transactions t
JOIN wp_products p
ON t.product_ID = p.ID
WHERE t.status = 'approved'
GROUP BY p.product_name
ORDER BY p.producer ASC, p.product_name ASC;

1 个答案:

答案 0 :(得分:3)

您可以通过使用变量枚举行来完成此操作:

SELECT avg(amount) as price, p.product_name, p.producer
FROM (SELECT t.*,
             (@rn := if(@p = t.Product_Id, @rn + 1,
                        if(@pr := t.Product_Id, 1, 1)
                       )
             ) as seqnum
      FROM wp_transactions t CROSS JOIN
           (SELECT @rn := 0, @p := 0) vars
      WHERE t.status = 'approved'
      ORDER BY t.product_ID, t.datetime
     ) t JOIN
     wp_products p
     ON t.product_ID = p.ID
WHERE seqnum <= 5
GROUP BY p.product_name
ORDER BY p.producer ASC, p.product_name ASC;