问题
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