从mysql表中获取产品摘要

时间:2015-03-17 10:45:11

标签: mysql

我必须编写一个对我来说有点过于复杂的查询。 我有带有这些样本记录的order_products表:

| ORDER_PRODUCTS_ID(auto)  | PRODUCT_ID    | PRICE | QUANTITY
| 1                        | 2             | 100   | 2
| 2                        | 2             | 100   | 3
| 3                        | 2             | 50    | 1
| 4                        | 3             | 200   | 4
| 5                        | 3             | 200   | 2

我需要查询关系,我可以按产品ID和价格总结所有最常购买的产品组(因为一个产品在每个订单中的价格可能与您在示例中看到的不同) 我需要结果如下:

PRODUCT_ID | QUANTITY_SUM | PRICE      | TOTAL SUM PRICE
3          | 6            | 200        | 400
2          | 5            | 100        | 200
2          | 1            | 50         | 50

我正在尝试查询:

select price, product_id, SUM(quantity) as quantity_sum ,
  price*quantity_sum as total_sum_price from dr_orders_products
   group by product_id , price order by quantity_sum desc

但是我给了我错误:'quantity_sum是未知列'。 我也在尝试这样的事情:

select price, product_id, SUM(quantity) as quantity_sum ,
      price*(select SUM(quantity) from dr_orders_products where product_id =product_id ans price = price  ) as total_sum_price from dr_orders_products
       group by product_id , price order by quantity_sum desc

但结果是一些更高的值。 我真的很感激这方面的帮助

3 个答案:

答案 0 :(得分:2)

试试这个

select price, product_id, SUM(quantity) as quantity_sum ,
       price*SUM(quantity) as total_sum_price 
from dr_orders_products
group by product_id , price 
order by SUM(quantity) desc

您无法在相同的选择中引用您在SELECT中创建的列。

答案 1 :(得分:1)

您无法在select语句中调用别名字段,因此要使用quality_sum,您需要将其称为原始名称。 但是您在数量字段中执行SUM,那么您只需要使用相同的数量来计算总数。

类似的东西:

select price, product_id, SUM(quantity) as quantity_sum ,
       price*SUM(quantity) as total_sum_price from dr_orders_products
group by product_id , price 
order by quantity_sum desc

答案 2 :(得分:1)

对于这种报告,您应该使用MySQL Views。视图就像经常更新其结果的查询一样。

CREATE VIEW product_summary AS
    SELECT 
        price, 
        product_id, 
        SUM(quantity) AS quantity_sum,
        price*SUM(quantity) AS total_sum_price
    FROM dr_orders_products
    GROUP BY product_id, price;

现在,如果你需要获得顶级产品,你可以

SELECT product_id FROM product_summary ORDER BY quantity_sum DESC LIMIT 1;

获得最常销售的产品(固定价格)。要获得产生最多收入的产品(以固定价格),您可以使用

SELECT product_id FROM product_summary ORDER BY total_sum_price DESC LIMIT 1;

当然,您可以通过从第一个视图创建第二个视图来进一步实现它,每个产品ID只包含一行:

CREATE VIEW product_distinct_summary AS 
    SELECT 
        product_id,
        SUM(quantity_sum) AS quantity_sum,
        SUM(total_sum_price) AS total_sum_price
    FROM product_summary;

通过在第二个视图中以固定价格对顶级产品使用前两个SELECT查询,您将获得最常销售或产生最多收入的产品,无论其个人价格如何。