Select 5 of each distinct value

蓝咒 提交于 2021-01-27 23:11:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!