MSSQL查询按权重选择顶部

时间:2014-09-01 10:41:22

标签: sql sql-server

请参阅下表。每个Targeted_Product_Id都有100 Recommended_Product_Id个。我希望按Weighting.选择前6 我尝试使用HAVING来实现它,但遗憾的是失败了。你能帮我构建这样的查询吗?

enter image description here

谢谢!

1 个答案:

答案 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