How can I take two rows for one Distinct value in postgresql?

独自空忆成欢 提交于 2019-12-25 04:13:38

问题


I want to get two rows of distinct column2 from following table.

demo_table 
id  | column1 | column2
 1  |    1    |    3
 2  |    2    |    3
 3  |    3    |    4
 4  |    4    |    3
 5  |    5    |    4
 6  |    6    |    3

When I preform this query

select distinct on (column2) * from demo_table 

it gives me out put as this

id  | column1 | column2
 5  |    5    |    4
 6  |    6    |    3

I am looking for query where I can get output as

id  | column1 | column2
 3  |    3    |    4
 5  |    5    |    4
 6  |    6    |    3
 4  |    4    |    3

it should give two row where column2 is distinct.


回答1:


Use row_number() for that:

select id, column1, column2
from (
  select id, column1, column2, 
         row_number() over (partition by column2 order by id) as rn
  from demo_table
) t 
where rn <= 2;


来源:https://stackoverflow.com/questions/39718851/how-can-i-take-two-rows-for-one-distinct-value-in-postgresql

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