如何获得前3个值mysql? Northwind数据库

时间:2015-07-01 08:37:08

标签: mysql sql northwind

我正在使用示例数据库Northwind在Toad中为mySQL做一些SQL练习。

此查询的目标是每月获得前3位客户。最重要的意义是他们花了最多钱。我能够加入表格并得出每个客户的所有支出,但我不能每个月都能获得最高价。

到目前为止,这是我的查询:

SELECT EXTRACT(MONTH FROM orders.OrderDate) AS `Month`,
orders.CustomerID,`order details`.OrderID, 
ROUND(SUM((`order details`.UnitPrice * `order details`.Quantity)*(1 - `order details`.Discount)),2) AS Cost
FROM `order details`
LEFT JOIN orders ON orders.OrderID = `order details`.OrderID
RIGHT JOIN customers ON customers.CustomerID = orders.CustomerID
GROUP BY orders.OrderID, orders.CustomerID, `Month`
ORDER BY Month DESC
LIMIT 3;

我觉得我可能需要某种循环来逐月递增,但我不知道它的格式,但什么是可行的解决方案?

1 个答案:

答案 0 :(得分:0)

for month in 6 5 4 ; do mysql -u root database_name -BNe "SELECT '"$month"' AS Month,orders.CustomerID, order_details.OrderID, ROUND(SUM((order_details.UnitPrice * order_details.Quantity)*(1 - order_details.Discount)),2) AS Cost FROM order_details LEFT JOIN orders ON orders.OrderID = order_details.OrderID RIGHT JOIN customers ON customers.CustomerID = orders.CustomerID where EXTRACT(MONTH FROM orders.OrderDate)=$month GROUP BY Month,orders.OrderID, orders.CustomerID ORDER BY Month DESC ,Cost Desc limit 3"; done