寻找最畅销的产品

时间:2013-12-04 15:07:03

标签: sql

我正在努力获得Margaret Peacock带来的最畅销产品 在11月份的大部分利润中,数据库是w3schools.com中的数据库,以防你们想要查看结构。这是我写的查询

SELECT e.FirstName, e.LastName, p.ProductName, od.Quantity, p.Price, o.OrderDate
FROM
  Employees e
  INNER JOIN Orders o ON e.EmployeeID = o.EmployeeID
  INNER JOIN OrderDetails od ON o.OrderID = od.OrderID
  INNER JOIN Products p ON od.ProductID = p.ProductID
WHERE 
  o.OrderDate BETWEEN '1996-11-01' AND '1996-11-30'
  AND e.FirstName = 'Margaret'
  AND e.LastName = 'Peacock'
GROUP BY
  e.FirstName,
  e.LastName,
  p.ProductName,
  od.Quantity,
  p.Price,
  o.OrderDate
ORDER BY p.Price DESC

结果如下:

FirstName   LastName    ProductName   Quantity   Price    OrderDate
Margaret    Peacock     Côte de Blaye      10             263.5   1996-11-22
Margaret    Peacock    Thüringer Rostbratwurs  35            123.79   1996-11-22
Margaret    Peacock    Rössle Sauerkraut       30              45.6   1996-11-22

1 个答案:

答案 0 :(得分:0)

最大功能通常有效,但您需要一些方法来了解获得实际利润的成本。

SELECT MAX(p.PRICE - p.[Cost Field])
FROM
  Employees e
  INNER JOIN Orders o ON e.EmployeeID = o.EmployeeID
  INNER JOIN OrderDetails od ON o.OrderID = od.OrderID
  INNER JOIN Products p ON od.ProductID = p.ProductID
WHERE 
  o.OrderDate BETWEEN '1996-11-01' AND '1996-11-30'
  AND e.FirstName = 'Margaret'
  AND e.LastName = 'Peacock'
GROUP BY
  e.FirstName,
  e.LastName,
  p.ProductName,
  od.Quantity,
  p.Price,
  o.OrderDate
ORDER BY p.Price DESC