我想創建一個以 1000 開頭并以一個單位遞增的序列。然后,將此序列應用于我的表“person”的變數“identification”。表“person”中的記錄數為958,因此默認情況下應增加到末尾。此外,我希望編號基于按降序排序的 Age 欄位。這就是說:“身份”欄位沒有記錄,它有 NULL 值。當我說按年齡排序時,我的意思是年齡最小的將分配 ID 號 1000,第二小的將分配 1001,依此類推。
我試圖做類似于以下的事情,但我沒有得到任何結果。我也試過在句子中間按年齡降序排列也沒有結果。任何想法只使用序列來做嗎?
TABLE PERSON (Name, Surname, City, Identification, Age)
CREATE SEQUENCE seq
START WITH 1000
INCREMENT BY 1
MINVALUE 1000;
ALTER TABLE person
ADD COLUMN identification integer DEFAULT nextval('seq');
uj5u.com熱心網友回復:
使用虛擬資料的快速示例:
create table age_seq_test(age int , fld_1 varchar, id integer);
insert into age_seq_test values (10, 'test'), (30, 'test2'), (20, 'test3');
select * from age_seq_test order by age;
age | fld_1 | id
----- ------- ------
10 | test | NULL
30 | test2 | NULL
20 | test3 | NULL
BEGIN;
with t as
(select age, row_number() over (order by age) as rn from age_seq_test)
update
age_seq_test AS ast
set
id = t.rn 999
from
t
where
ast.age = t.age ;
select * from age_seq_test order by age;
age | fld_1 | id
----- ------- ------
10 | test | 1000
20 | test3 | 1001
30 | test2 | 1002
--COMMIT/ROLLBACK depending on what the SELECT shows.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397780.html
標籤:PostgreSQL的
上一篇:為什么DockerCompose不尊重我的POSTGRES_USER環境變數?
下一篇:查詢的執行計劃
