我有3张桌子:
我想计算每年销售的产品总数。为此,我编写了以下查询:
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
它给了我以下结果集:
它给出了按产品分组的总金额。但我想改为按年份分组总金额。
因此,对于2016年(以及其他年份),我希望得到以下结果:
2016 10,606 (since 6478 + 632 + 2072 + 1424)
但是我无法计算按年分组的总金额,因为每种产品的价格都不同。那么如何修改现有查询以获取每年售出的产品总数?
如果仅靠MySQL无法实现,那么我会毫不犹豫地使用PHP。
答案 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