Postgresql - 使用不同时保留相对位置

Postgresql - Preserve relative position when using distinct

我 运行 一个返回 table 这样的查询。

 d |  e  | f  
---+-----+----
 2 | 103 | C
 6 | 201 | AB
 1 | 102 | B
 1 | 102 | B
 1 | 102 | B
 1 | 102 | B
 1 | 102 | B
 3 | 105 | E
 3 | 105 | E
 3 | 105 | E

我想要的是获得不同的行但顺序。基本上我想要这个:

2 | 103 | C
6 | 201 | AB
1 | 102 | B
3 | 105 | E

我尝试了 distinctgroup by,但它们并不总是保留位置(它们为我遇到的其他一些情况保留了位置)。关于如何轻松完成此操作或需要使用其他功能(例如 rank?

)的任何想法

使用案例:

order by case when f=C then 1 when f=AB then 2
when f=B then 3 when f=E then 5 else null end

您可以尝试order by ctid列,它描述了一行的物理位置,来标识一行。

The physical location of the row version within its table. Note that although the ctid can be used to locate the row version very quickly, a row's ctid will change if it is updated or moved by VACUUM FULL. Therefore ctid is useless as a long-term row identifier. The OID, or even better a user-defined serial number, should be used to identify logical rows.

使用 row_numberwindows 函数 使行号达到 ctid.

然后得到rn = 1order by ctid

CREATE TABLE T(
  d int,
  e int,
  f varchar(5)
);

insert into t values (2,103, 'C');
insert into t values (6,201, 'AB');
insert into t values (1,102, 'B');
insert into t values (1,102, 'B');
insert into t values (1,102, 'B');
insert into t values (1,102, 'B');
insert into t values (1,102, 'B');
insert into t values (3,105, 'E');
insert into t values (3,105, 'E');
insert into t values (3,105, 'E');

查询 1:

select d,e,f 
from (
  select d,e,f,ctid,row_number() over(partition by d,e,f order by ctid) rn
  FROM T
)t1
where rn = 1
order by ctid

Results:

| d |   e |  f |
|---|-----|----|
| 2 | 103 |  C |
| 6 | 201 | AB |
| 1 | 102 |  B |
| 3 | 105 |  E |

SQL 表表示 无序 集合。没有顺序,除非您有一个带有列或表达式的显式 order by

如果你有这样的顺序,你可以使用 group by:

做你想做的事
select d, e, f
from t
group by d, e, f
order by min(a);  -- assuming a is the column that specifies the ordering