【发布时间】:2014-12-02 05:51:27
【问题描述】:
我制作了一份“在每个国家/地区销售了哪些产品以及销售了多少产品”的报告。我正在使用 Northwind 数据库,SQL Server 2012。
以下是代码:
SELECT
o.ShipCountry AS 'Country',od.ProductID,
p.ProductName, p.UnitPrice,
SUM(od.Quantity) AS 'Number of Units Sold'
FROM
Products p
INNER JOIN
[Order Details] od ON od.ProductID = p.ProductID
INNER JOIN
Orders o ON o.OrderID = od.OrderID
GROUP BY
p.ProductName, od.ProductID, p.UnitPrice, o.ShipCountry
ORDER BY
o.ShipCountry, 'Number of Units Sold' DESC
结果显示超过 900 行,每个国家/地区大约有 10 到 20 行:
但我想更上一层楼,现在我想生产“每个国家/地区销售的前 3 名产品”
所以我尝试了ROW_NUMBER() OVER (PARTITION BY,但我在使用Row_NUMBER()时很笨拙
以下是我的错误代码:
WITH CTE AS
(
SELECT
o.ShipCountry AS 'Country',od.ProductID,
p.ProductName, p.UnitPrice,
SUM(od.Quantity) AS 'Number of Units Sold',
ROW_NUMBER() OVER (PARTITION BY o.ShipCountry ORDER BY ('Number of Units Sold') DESC) AS 'Number of Units Sold'
FROM
Products p
INNER JOIN
[Order Details] od ON od.ProductID = p.ProductID
INNER JOIN
Orders o ON o.OrderID = od.OrderID)
SELECT
'Country', ProductID,
ProductName, UnitPrice, 'Number of Units Sold'
FROM
CTE
WHERE
'Number of Units Sold' < 4
GROUP BY
p.ProductName, od.ProductID, p.UnitPrice, o.ShipCountry
ORDER BY
o.ShipCountry DESC
【问题讨论】:
标签: sql sql-server tsql sql-server-2012 row-number