查询不带有max函数的关联值(Northwinds数据库)

时间:2017-03-12 20:56:26

标签: mysql sql max greatest-n-per-group northwind

我正在尝试获得每个类别总价值最高的产品。我按类别获得了正确的'Grossed'金额,但它似乎没有带上正确的'ProductID'和'ProductName'。

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;

任何反馈都会有所帮助。 谢谢!

1 个答案:

答案 0 :(得分:0)

考虑与 CategoryID Grossed 字段匹配的两个聚合查询的派生表:

SELECT p.*, c.CategoryName, ROUND(g.MaxGrossed) AS HighestGrossed
FROM category c
INNER JOIN
  (SELECT subp.ProductID, subp.ProductName, subp.CategoryID,
          SUM(((od.UnitPrice * od.Quantity) - 
              ((od.UnitPrice * od.Quantity) * od.Discount))) AS Grossed
   FROM northwind.`order details` AS od
   INNER JOIN products AS subp ON subp.ProductID = od.ProductID
   GROUP BY subp.ProductID) As p
ON c.CategoryID = p.CategoryID

INNER JOIN
   (SELECT subg.CategoryID, MAX(subg.Grossed) AS MaxGrossed
    FROM
      (SELECT subp.ProductID, subp.ProductName, subp.CategoryID,
              SUM(((od.UnitPrice * od.Quantity) - 
                  ((od.UnitPrice * od.Quantity) * od.Discount))) AS Grossed
       FROM northwind.`order details` AS od
       INNER JOIN products AS subp ON subp.ProductID = od.ProductID
       GROUP BY subp.ProductID) AS subg
    GROUP BY subg.CategoryID) AS g
ON p.CategoryID = g.CategoryID AND p.Grossed = g.MaxGrossed

您甚至可以将计算 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