在PostgreSQL中,如何为一个唯一值取两行? [英] How can I take two rows for one Distinct value in postgresql?

查看:96
本文介绍了在PostgreSQL中,如何为一个唯一值取两行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从下表中获得两行不同的column2。

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

当我执行此查询时

select distinct on (column2) * from demo_table 

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

应在列2不同的地方给出两行。

it should give two row where column2 is distinct.

推荐答案

为此使用row_number():

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;

这篇关于在PostgreSQL中,如何为一个唯一值取两行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆