我正在编写一个查询,以检索购买了大部分图书的网站上最受欢迎的用户。该数字应该是动态的,如前100名,前50名或前10名用户。我为此目的写了下面的查询,但发现了一个问题:
DECLARE @TOPNumber INT
SET @TOPNumber = 10
SELECT
S.UserName,
S.Email,
TOPST.NumberOfPurchase
FROM
Subscriber S
JOIN
(
SELECT ROW_NUMBER() Over(order by [FK_Subscriber])as Slno, FK_Subscriber,COUNT(*) NumberOfPurchase FROM SubscriberPurchase
GROUP BY FK_Subscriber
--ORDER BY FK_Subscriber
) TOPST ON S.PK_SubscriberID = TOPST.FK_Subscriber AND TOPST.Slno <= @TOPNumber
ORDER BY TOPST.NumberOfPurchase DESC
正如您所看到的那样,内部查询中的ORDER BY子句被注释,因为我无法在该位置使用它。如果我可以,那么查询给我想要的结果。
任何人都可以帮助如何做到这一点。我在数据库中有数百万条记录,因此需要适当的优化
答案 0 :(得分:1)
请改为尝试:
WITH CTE
AS
(
SELECT
S.UserName,
S.Email,
p.NumberOfPurchase,
ROW_NUMBER() Over(PARTITION BY FK_Subscriber
ORDER BY [FK_Subscriber])as Slno,
FROM Subscriber S
INNER JOIN
(
SELECT FK_Subscriber, COUNT(*) NumberOfPurchase
FROM SubscriberPurchase
GROUP BY FK_Subscriber
) AS p ON S.PK_SubscriberID = p.FK_Subscriber
)
SELECT
UserName,
Email,
NumberOfPurchase
FROM CTE
WHERE Slno <= @TOPNumber
ORDER BY NumberOfPurchase DESC