gpt4 book ai didi

MySQL - 将 ID 匹配到 Max of Count ("Need"更优雅的解决方案)

转载 作者:行者123 更新时间:2023-11-28 23:58:16 24 4
gpt4 key购买 nike

是否有更好的方法来执行以下操作:

SELECT ProductID, MAX(a.countProductID)
FROM
(
SELECT ProductID, COUNT(ProductID) as countProductID
FROM SalesOrderDetail
LEFT JOIN Product USING (ProductID)
GROUP BY ProductID
) as a
WHERE a.countProductID = (SELECT MAX(x.countProductID) FROM
(
SELECT ProductID, COUNT(ProductID) as countProductID
FROM SalesOrderDetail
LEFT JOIN Product USING (ProductID)
GROUP BY ProductID
) as x
);

因为我两次使用相同的子查询。但是我无法从 WHERE 子句访问第一个。

最佳答案

我猜任务是找到一个或多个销售量最大的产品。首先,您不应该加入 PRODUCT 表,因为您需要的所有信息都在 SalesOrderDetail 表中。然后使用 LIMIT 1 找到最大计数并使用 HAVING 选择所有具有最大计数的产品:

SELECT ProductID, COUNT(ProductID) as countProductID
FROM SalesOrderDetail
GROUP BY ProductID
HAVING COUNT(ProductID) = (SELECT COUNT(ProductID) as countProductID
FROM SalesOrderDetail
GROUP BY ProductID
ORDER BY countProductID DESC
LIMIT 1 )

关于MySQL - 将 ID 匹配到 Max of Count ("Need"更优雅的解决方案),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30870431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com