Mysql 查询未带来与max函数关联的值(Northwinds数据库)
我正试图得到每一类总价值最高的产品。我按类别获得了正确的“总收入”金额,但它似乎没有带来正确的“ProductID”和“ProductName”Mysql 查询未带来与max函数关联的值(Northwinds数据库),mysql,sql,max,greatest-n-per-group,northwind,Mysql,Sql,Max,Greatest N Per Group,Northwind,我正试图得到每一类总价值最高的产品。我按类别获得了正确的“总收入”金额,但它似乎没有带来正确的“ProductID”和“ProductName” SELECT c.CategoryName, prodGross.ProductID, prodGross.ProductName, MAX(ROUND(Grossed, 2)) AS Grossed FROM categories AS c JOIN (SELECT
SELECT
c.CategoryName,
prodGross.ProductID,
prodGross.ProductName,
MAX(ROUND(Grossed, 2)) AS Grossed
FROM
categories AS c
JOIN
(SELECT
p.ProductID,
p.ProductName,
p.CategoryID,
SUM(((od.UnitPrice * od.Quantity) - ((od.UnitPrice * od.Quantity) * od.Discount))) AS Grossed
FROM
northwind.`order details` AS od
JOIN products AS p ON p.ProductID = od.ProductID
GROUP BY p.ProductID) AS prodGross ON prodGross.CategoryID = c.CategoryID
GROUP BY c.CategoryName;
任何反馈都会有帮助。
谢谢大家! 考虑与CategoryID和Grossed字段匹配的聚合查询的派生表: 您甚至可以将计算总收入的重复聚合保存为单独的存储视图,并在此查询中引用它:
SELECT p.*, c.CategoryName, ROUND(g.MaxGrossed) AS HighestGrossed
FROM category c
INNER JOIN ProdGrossedView As p
ON c.CategoryID = p.CategoryID
INNER JOIN
(SELECT v.CategoryID, MAX(v.Grossed) AS MaxGrossed
FROM ProdGrossedView v
GROUP BY v.CategoryID) AS g
ON p.CategoryID = g.CategoryID AND p.Grossed = g.MaxGrossed
这就是这个问题的一个例子,它有几十种关于堆栈溢出的解决方案。现在我得到了太多的数据。类别显示所有产品和总金额。我不知道如何才能得到最高的价值。考虑把这个MAX(圆(GROSE,2))作为最大值(圆(PrdGrut. GrScript,2))重写为Max。
SELECT p.*, c.CategoryName, ROUND(g.MaxGrossed) AS HighestGrossed
FROM category c
INNER JOIN ProdGrossedView As p
ON c.CategoryID = p.CategoryID
INNER JOIN
(SELECT v.CategoryID, MAX(v.Grossed) AS MaxGrossed
FROM ProdGrossedView v
GROUP BY v.CategoryID) AS g
ON p.CategoryID = g.CategoryID AND p.Grossed = g.MaxGrossed