选择每个不同值中的5个

时间:2013-08-14 12:27:24

标签: sql ruby-on-rails postgresql activerecord

我在PostgreSQL中有以下表格:

|  a  |  b  |  c  |
===================
| 'w' |  2  |  3  |
| 'w' |  7  |  2  |
| 'w' |  8  |  1  |
| 'w' |  3  |  6  |
| 'w' |  0  |  8  |
| 'w' |  2  |  9  |
| 'w' |  2  |  9  |
| 'z' |  4  |  9  |
| 'z' |  0  |  9  |
| 'z' |  0  |  8  |
| 'z' |  3  |  6  |
| 'z' |  2  |  7  |
| 'z' |  3  |  1  |
| 'z' |  3  |  2  |
| 'z' |  3  |  3  |

我想选择所有记录,但是将它们限制为列a中每个不同值的5条记录 结果如下:

|  a  |  b  |  c  |
===================
| 'w' |  2  |  3  |
| 'w' |  7  |  2  |
| 'w' |  8  |  1  |
| 'w' |  3  |  6  |
| 'w' |  0  |  8  |
| 'z' |  4  |  9  |
| 'z' |  0  |  9  |
| 'z' |  0  |  8  |
| 'z' |  3  |  6  |
| 'z' |  2  |  7  |

在RoR中实现这一目标的最有效方法是什么?谢谢!

1 个答案:

答案 0 :(得分:3)

您可以使用row_number,但您必须指定订单,否则您将获得无法预测的结果

   with cte as (
       select
           *,
           row_number() over(partition by a order by b, c) as row_num
       from table1
   )
   select a, b, c
   from cte
   where row_num <= 5