如何计算每年售出的产品总数?

时间:2019-10-25 06:47:04

标签: mysql

我有3张桌子:

  1. 产品(具有产品ID,价格等)
  2. 订单(具有订单ID,日期等)
  3. orders_products(具有详细的订单信息,例如产品数量等)

我想计算每年销售的产品总数。为此,我编写了以下查询:

SELECT YEAR(`o`.`date_purchased`) AS year,
       SUM(`op`.`products_quantity`) AS TotalUnits,
       `p`.`products_id`,
       `p`.`products_price` AS price,
       ( SUM(`op`.`products_quantity`) * `p`.`products_price` ) AS TotalAmount
FROM   `orders` AS `o`
       INNER JOIN `orders_products` AS `op`
               ON `o`.`orders_id` = `op`.`orders_id`
       INNER JOIN `products` AS `p`
               ON `op`.`products_id` = `p`.`products_id`
GROUP  BY `p`.`products_id`
ORDER  BY year

它给了我以下结果集:

enter image description here

它给出了按产品分组的总金额。但我想改为按年份分组总金额。

因此,对于2016年(以及其他年份),我希望得到以下结果:

2016     10,606 (since 6478 + 632 + 2072 + 1424)

但是我无法计算按年分组的总金额,因为每种产品的价格都不同。那么如何修改现有查询以获取每年售出的产品总数?

如果仅靠MySQL无法实现,那么我会毫不犹豫地使用PHP。

1 个答案:

答案 0 :(得分:2)

您只需要将数量和价格的乘积带到SUM中,以便每种产品的数量乘以其自己的价格:

SELECT YEAR(`o`.`date_purchased`) AS year,
       SUM(`op`.`products_quantity`) AS TotalUnits,
       SUM(`op`.`products_quantity` * `p`.`products_price`) AS TotalAmount
FROM   `orders` AS `o`
INNER JOIN `orders_products` AS `op` ON `o`.`orders_id` = `op`.`orders_id`
INNER JOIN `products` AS `p` ON `op`.`products_id` = `p`.`products_id`
GROUP  BY year
ORDER  BY year