Oracle查询以查找每组的前2项

时间:2016-06-26 17:27:37

标签: sql oracle greatest-n-per-group

我想在sracle查询中找到oracle中每组的前2项 该表包含:

P_id Price GroupX
1     10    a 
2     5     a
3     5     a
4     4     b
5     8     b
6     6     b

输出应为:

P_id Price  GroupX
1     10      a
2     5       a
5     8       b
6     6       b

我试过的是:

Select * from table
group by GroupX
order by price desc
limit 2

2 个答案:

答案 0 :(得分:0)

怎么样

 Select  rnk,P_id, Price, GroupX 
        from (
             select P_id, Price, GroupX,
                  RANK () OVER (PARTITION BY GroupX
                           ORDER BY  Price DESC
               ) AS rnk
             from table
             )
        where rnk <= 2;

答案 1 :(得分:0)

您可以使用ROW_NUMBER()分析函数:

SELECT p_id,
       price,
       GroupX
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER ( PARTITION BY groupX
                             ORDER BY Price DESC ) AS rn
  FROM   table_name t
)
WHERE rn <= 2;