请参阅下表。每个Targeted_Product_Id
都有100 Recommended_Product_Id
个。我希望按Weighting.
选择前6 我尝试使用HAVING
来实现它,但遗憾的是失败了。你能帮我构建这样的查询吗?
谢谢!
答案 0 :(得分:2)
;WITH RemoveDuplicatesCTE AS
(
SELECT Targeted_Product_Id,
Recommended_Product_Id,
Weighting
ROW_NUMBER() OVER(PARTITION BY Targeted_Product_Id,Recommended_Product_Id ORDER BY Targeted_Product_Id,Recommended_Product_Id) AS rn
FROM Targeted_Product
)
,ProductsCTE AS
(
SELECT Targeted_Product_Id,
Recommended_Product_Id,
Weighting
ROW_NUMBER() OVER(PARTITION BY Targeted_Product_Id ORDER BY Weighting DESC) AS rn
FROM RemoveDuplicatesCTE
WHERE rn = 1
)
SELECT Targeted_Product_Id,
Recommended_Product_Id,
Weighting
FROM ProductsCTE
WHERE rn<=6
ORDER BY Targeted_Product_Id,
rn DESC