2

我在 PostgreSQL 中有下表:

| 一个 | 乙 | 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 |

我想选择所有记录,但对于 column 中的每个不同值,它们限制为 5 条记录a
所以结果看起来像:

| 一个 | 乙 | 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 中实现这一目标的最有效方法是什么?谢谢!

4

1 回答 1

3

you can use row_number, but you have to specify order or you will get unpredictable resutls

   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
于 2013-08-14T12:33:54.790 回答