SQL / PHP - 查找特定项目总和的平均值

时间:2017-04-01 20:19:58

标签: mysql sql

好吧,SQL不是我的母语,我无法处理我的问题。 我有一张桌子。

+------------+--------+-----------+
| Item name: | Price: | Quantity: |
+------------+--------+-----------+
| Cherry     |     20 |        11 |
| Cherry     |     19 |         9 |
| Apple      |     20 |         2 |
| Apple      |     19 |         1 |
| Cherry     |     16 |         2 |
| Apple      |     15 |         1 |
| Apple      |     21 |         1 |
| Apple      |     14 |         4 |
| Cherry     |     11 |         1 |
+------------+--------+-----------+

我需要找到5个最便宜的苹果的平均价格。谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

如果我理解正确,你想获得价格最低的前5个苹果并找到加权平均价格。您可以在此处使用用户变量。

select
    sum(price * quantity) / sum(quantity) as average_price
from (
    select
        price,
        case when diff >= 0 then quantity else quantity + diff end as quantity
    from (
        select t.*,
            @required := @required - quantity as diff
        from your_table t
        cross join (select @required := 5) x
        where item_name = 'Apple'
        order by price
    ) t where quantity + diff > 0
) t;

请参阅此演示 - http://rextester.com/XZQ74947

您可以单独运行子查询,看看它是如何工作的。