PostgreSQL:如何删除偶数行
PostgreSQL: how to remove even rows
我的 table 中的行结构如下:
col1 col2 col3
a b c
a b c
a b c
d e f
d e f
我用 row_number
列举了它们
col1 col2 col3 rn
a b c 1
a b c 2
a b c 3
d e f 1
d e f 2
并且我想删除每行具有偶数 rn 值的行。
我该怎么做?我的想法是使用 row_number 但也许还有另一种解决方案。
这很痛苦,因为您没有唯一的值来标识每一行。您可以即时使用 ctid
来执行此操作:
delete from t
using (select t2.*, ctid as orig_ctid,
row_number() over (partition by col1, col2, col3 order by ?) as seqnum
from t t2
) t2
where t2.orig_ctid = t.ctid and
mod(seqnum, 2) = 0;
不过,拥有一个连续专栏比依赖 ctid
更好。
我的 table 中的行结构如下:
col1 col2 col3
a b c
a b c
a b c
d e f
d e f
我用 row_number
列举了它们col1 col2 col3 rn
a b c 1
a b c 2
a b c 3
d e f 1
d e f 2
并且我想删除每行具有偶数 rn 值的行。
我该怎么做?我的想法是使用 row_number 但也许还有另一种解决方案。
这很痛苦,因为您没有唯一的值来标识每一行。您可以即时使用 ctid
来执行此操作:
delete from t
using (select t2.*, ctid as orig_ctid,
row_number() over (partition by col1, col2, col3 order by ?) as seqnum
from t t2
) t2
where t2.orig_ctid = t.ctid and
mod(seqnum, 2) = 0;
不过,拥有一个连续专栏比依赖 ctid
更好。