我正在尝试计算每种产品的订单数量的总和,然后仅显示订单数量最多的产品。因此,如果2个产品的订单数量相同,则查询应显示两者,否则只显示最高订单。
我的架构如下:
Product(
**product_id**,
product_category,
client_id,
num_order
)
我非常感谢一些帮助,因为我是MySql的初学者并且正在努力学习。
非常感谢提前!
答案 0 :(得分:4)
使用子查询尝试此方法:
SELECT product_id
FROM product
GROUP BY product_id
HAVING SUM(num_order) = (
SELECT SUM(num_order)
FROM product
GROUP BY product_id
ORDER BY SUM(num_order) DESC
LIMIT 1
)
这是使用MAX
的变体:
SELECT product_id
FROM product
GROUP BY product_id
HAVING SUM(num_order) = (
SELECT MAX(num_order)
FROM
(
SELECT SUM(num_order) AS num_order
FROM product
GROUP BY product_id
) T1
)