如何在 postgresql 中为一个 Distinct 值取两行?
How can I take two rows for one Distinct value in postgresql?
我想从以下 table.
中获取两行不同的 column2
demo_table
id | column1 | column2
1 | 1 | 3
2 | 2 | 3
3 | 3 | 4
4 | 4 | 3
5 | 5 | 4
6 | 6 | 3
当我执行此查询时
select distinct on (column2) * from demo_table
它给了我这样的输出
id | column1 | column2
5 | 5 | 4
6 | 6 | 3
我正在寻找可以获得输出的查询
id | column1 | column2
3 | 3 | 4
5 | 5 | 4
6 | 6 | 3
4 | 4 | 3
它应该给出两行,其中 column2 是不同的。
为此使用 row_number():
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;
我想从以下 table.
中获取两行不同的 column2demo_table
id | column1 | column2
1 | 1 | 3
2 | 2 | 3
3 | 3 | 4
4 | 4 | 3
5 | 5 | 4
6 | 6 | 3
当我执行此查询时
select distinct on (column2) * from demo_table
它给了我这样的输出
id | column1 | column2
5 | 5 | 4
6 | 6 | 3
我正在寻找可以获得输出的查询
id | column1 | column2
3 | 3 | 4
5 | 5 | 4
6 | 6 | 3
4 | 4 | 3
它应该给出两行,其中 column2 是不同的。
为此使用 row_number():
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;