Sql server SQL Server:如何按国家/地区获取前5名订单的总和
这是我第一次来这里:p 我有SQL Server练习 根据Northwind客户居住的国家/地区,按国家/地区显示5个最高采购订单的总和。结果应分为两列:国家、金额 我试过:Sql server SQL Server:如何按国家/地区获取前5名订单的总和,sql-server,Sql Server,这是我第一次来这里:p 我有SQL Server练习 根据Northwind客户居住的国家/地区,按国家/地区显示5个最高采购订单的总和。结果应分为两列:国家、金额 我试过: SELECT vt.ShipCountry, vt.suma FROM (SELECT o.ShipCountry, SUM( UnitPrice * Quantity * (1-discount)) as suma, RANK() OVER (PA
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;
这两个查询具有相同的行为请尝试以下操作:
-- 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
这应该对你有好处-我希望 试试这个:
-- 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
这应该对你有好处-我希望