2015-09-25 31 views
1

這是我第一次來這裏:pSQL Server:如何獲得按國家排名前5位的SUM

我有SQL Server實踐。

根據Northwind客戶所在的國家/地區,顯示按國家/地區劃分的5個最高採購訂單的總和。結果應該在兩列呈現:全國,量

我想:

SELECT 
    vt.ShipCountry, vt.suma 
FROM 
    (SELECT 
     o.ShipCountry, 
     SUM(UnitPrice * Quantity * (1-discount)) as suma, 
     RANK() OVER (PARTITION BY SUM(UnitPrice * Quantity * (1-discount)) ORDER BY shipCountry DESC) AS Rank 
    FROM 
     orders o 
    JOIN 
     [Order Details] od ON o.OrderID = od.OrderID 
    GROUP BY 
     o.ShipCountry) as vt 
WHERE 
    Rank <= 5 
GROUP BY 
    vt.ShipCOUNTRY, vt.suma 

但是,它檢索我每個國家的所有訂單的總和,只需要前5每個國家

這是另一個,同樣的問題。

SELECT 
    ShipCountry, rk, amount 
FROM 
    (SELECT 
     o.ShipCountry, 
     SUM(UnitPrice * Quantity * (1-discount)) amount, 
     DENSE_RANK() OVER(PARTITION BY o.ShipCountry ORDER BY SUM(UnitPrice * Quantity * (1-discount)) DESC) AS rk 
    FROM 
     Orders o 
    JOIN 
     [Order Details] od ON o.OrderID = od.OrderID 
     GROUP BY 
     o.shipCountry) AS L 
WHERE 
    rk <= 5; 

這兩個查詢具有相同的行爲

回答

0

試試這個:

-- first, sum up the total amount of each order 
;WITH OrderDetails AS 
(
    SELECT 
     o.OrderID, 
     TotalOrderAmount = SUM(UnitPrice * Quantity * (1 - discount)) 
    FROM 
     orders o 
    INNER JOIN 
     [Order Details] od ON o.OrderID = od.OrderID 
    GROUP BY 
     o.OrderID 
), 
-- secondly, join the "ShipCountry" to the order totals, 
-- and define a ROW_NUMBER() for each country, based on 
-- total order amount 
OrderPerCountry AS 
(
    SELECT 
     o.ShipCountry, 
     od.TotalOrderAmount, 
     RowNum = ROW_NUMBER() OVER(PARTITION BY o.ShipCountry ORDER BY od.TotalOrderAmount DESC) 
    FROM 
     OrderDetails od 
    INNER JOIN 
     dbo.Orders o ON o.OrderID = od.OrderID 
) 
SELECT * 
FROM OrderPerCountry 
WHERE RowNum <= 5 

這應該爲你做的伎倆 - 我希望!