我想使用Rank()
查询每个客户的最高折扣级别 。
但是有些数据丢失了,我不知道为什么......
(我使用了数据库 Northwind )
这是我试过的脚本..
WITH CTE AS
(SELECT ProductID, CustomerID, Discount,
RANK() over (partition by CustomerID order by Discount desc) as rank
FROM Orders
JOIN [Order Details]
ON Orders.OrderID= [Order Details].OrderID
)
SELECT Distinct ProductID, CustomerID, Discount
FROM CTE
WHERE
Discount>0.1 and
ProductID between 60 and 65 and
rank=1
order by CustomerID
在此过程之前, 我事先尝试过这个脚本
select ProductID, customerID, Discount
from Orders
join [Order Details]
on orders.OrderID = [Order details].OrderID
where
Discount>0.1 and
ProductID between 60 and 65
order by ProductID, CustomerID
go
我手动编辑以获得每个客户的最高折扣级别。 我应该有大约32行(这取决于我是否删除重复的数据) 但是当我运行第一个脚本时,我只得到15行.. 我怎么解决这个问题?任何帮助将不胜感激。
答案 0 :(得分:1)
您在应用过滤器之前计算RANK()
,这意味着过滤器可以删除某些Rank() = 1
行。尝试将过滤器移到CTE
。
;WITH cte
AS (SELECT productid,
customerid,
discount,
Rank()
OVER (
PARTITION BY customerid
ORDER BY discount DESC) AS [rank]
FROM orders
JOIN [order details]
ON orders.orderid = [order details].orderid
WHERE discount > 0.1
AND productid BETWEEN 60 AND 65)
SELECT DISTINCT productid,
customerid,
discount
FROM cte
WHERE [rank] = 1
ORDER BY customerid