每个项目的表中排名前3位

时间:2013-12-05 06:33:43

标签: sql oracle

在我的场景中,我在oracle中列出了项目销售数量。我想应用一个查询来获得每个项目的前3个销售数量。对此有什么疑问。

Item_Sale表

item_No Sold_Qty
1   5
1   6
1   2
1   8
1   9
2   7
2   8
2   4
2   5
2   8
2   7
2   6
2   1
2   2
2   8
3   7
3   2
3   4
3   2
3   6

现在我想看到每个项目的前三名出售数量

期望的结果是

item_no Top3_Sold_Qty
1   9
1   8
1   7
2   8
2   7
2   6
3   7
3   6
3   4

3 个答案:

答案 0 :(得分:2)

首先,您需要选择不同的值

SELECT item_No, Sold_Qty FROM
(SELECT item_No, Sold_Qty, ROW_NUMBER() OVER(PARTITION BY iten_No ORDER BY Sold_Qty DESC) AS Rank FROM
(SELECT DISTINCT item_No, Sold_Qty FROM Item_Sale) Temp) Temp2
WHERE Rank< 4

答案 1 :(得分:0)

with cte as 
(
select item_no,Sold_qty,row_number() over (partition by item_no order by sold_qty desc) as rank1 from table
)

select * from cte where rank1<=3 order by item_no,Sold_qty desc

答案 2 :(得分:0)

SELECT item_No, Sold_Qty
FROM
(
  SELECT
    item_No, Sold_Qty,
    ROW_NUMBER() OVER (PARTITION BY item_No ORDER BY Sold_Qty desc) rn
  FROM Item_Sale
)
WHERE rn <= 3
ORDER BY item_No;

fiddle demo

评论后(针对不同的值):

SELECT DISTINCT item_No, Sold_Qty
FROM
(
   SELECT
     item_No, Sold_Qty,
     DENSE_RANK() OVER (PARTITION BY item_No ORDER BY Sold_Qty desc) rn
   FROM Item_Sale
)
WHERE rn <= 3
ORDER BY item_No;