2017-06-02 135 views
0

我有表像SQL - PostgreSQL中,基於其他列的增量列的值

create table test(employee integer NOT NULL, code character varying(200), number integer) 

我想自動遞增列「數量」上的每個插入記錄

insert into test(employee, code) values(17,'bangalore') 
insert into test(employee, code) values(17,'bangalore') 
insert into test(employee, code) values(17,'mumbai') 

我想導致像

employee code  number 
17   bangalore 1 
17   bangalore 2 
17   bangalore 3 
17   mumbai  1 
17   mumbai  2 
17   bangalore 4 
17   mumbai  3 
18   bangalore 1 
18   bangalore 2 
18   mumbai  1 
18   mumbai  2 
+0

做**不**發佈代碼或註釋中的其他信息。 ** [編輯] **你的問題。 –

+2

你爲什麼要存儲這些信息?您可以在檢索數據時輕鬆生成這些數字。 –

+0

我想存儲多個地方引用的相同數據 –

回答

0
create table test (employee integer NOT NULL, code character varying(200), number integer) 

    insert into test(employee, code, number) values(17,'bangalore',(select coalesce(max(number) + 1,1) from test where employee = 17 and code = 'bangalore')); 
    insert into test(employee, code, number) values(17,'bangalore',(select coalesce(max(number) + 1,1) from test where employee = 17 and code = 'bangalore')); 
    insert into test(employee, code, number) values(17,'mumbai',(select coalesce(max(number) + 1,1) from test where employee = 17 and code = 'mumbai')); 
+0

我會使用'max'而不是'count'。如果某些行被刪除會怎麼樣? –

+0

@LaurenzAlbe,是的,你是對的。我們必須改變count(*)+ 1來合併(max(number)+ 1,1)。 –

+0

這對單插入正常工作,但我想批量更新。 –

0

對於一批上升d的數據,請嘗試下面的方法是否有用。

創建臨時表test2的

create table test2(employee integer NOT NULL, code character varying(200)) 

insert into test2(employee, code) values(17,'bangalore') 
insert into test2(employee, code) values(17,'bangalore') 
insert into test2(employee, code) values(17,'mumbai') 

插入到實際表遞增的數字

insert into test(employee, code, number) 
select employee, code, row_number() over (partition by code) from test2 

沿着您可以通過條款像主鍵列或類似CREATED_DATE另一列包括順序:

over (partition by code order by created_date)