问题
I have the following table in 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 |
I want to select all records, but limit them to 5 records for each distinct value in column a
.
So the result would look like:
| 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 |
What is the most effecient way to achieve that in RoR? Thanks!
回答1:
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
来源:https://stackoverflow.com/questions/18231744/select-5-of-each-distinct-value