在 postgres 中选择并插入计数器

问题描述 投票:0回答:2

我想从一个表中选择记录并插入到另一个表中。这是我的表1

create table temp 
(
    seq varchar(20),
    prefix varchar(20)
);

insert into temp values ('AAA','A'); // counter should be 1 as combo of AAA and A is 1
insert into temp values ('AAA','A'); // counter should be 2 as combo of AAA and A is 2
insert into temp values ('BBB','B'); // counter should be 1 as combo of BBB and B is 1
insert into temp values ('BBB','B'); // counter should be 2 as combo of BBB and B is 2
insert into temp values ('BBB','C'); // counter should be 1 as combo of BBB and C is 1

现在从 temp 插入到 temp_1

 INSERT INTO temp_1 (seq,prefix,counter)  
     SELECT 
         seq, prefix, 
         (SELECT COUNT(*) FROM temp t 
          WHERE t.seq = t2.seq AND t.prefix = t2.prefix)
     FROM temp t2;  

This is what inserted

sql postgresql postgresql-9.1 postgresql-9.5
2个回答
0
投票

您可以为每组

row_number
使用
seq,prefix

INSERT INTO temp_1 (seq,prefix,counter)  
 SELECT seq, prefix, row_number() OVER (partition by seq, prefix)
 FROM tmp;

示例:

WITH src(seq,prefix) as ( values ('AAA','A'),('AAA','A'),('BBB','B'),('BBB','B'),('BBB','C'),('BBB','B'))
SELECT seq,prefix,row_number() OVER (partition by seq,prefix)
FROM src;

 seq | prefix | row_number
-----+--------+------------
 AAA | A      |          1
 AAA | A      |          2
 BBB | B      |          1
 BBB | B      |          2
 BBB | B      |          3
 BBB | C      |          1
(6 rows)

0
投票

很可能您需要窗口函数 row_number() 来实现此目的。至少它给了你你正在寻找的结果:

INSERT INTO temp_1 (seq,prefix,counter)  
SELECT seq
    ,prefix
    , row_number() OVER (PARTITION BY prefix) as row_number
FROM temp;
© www.soinside.com 2019 - 2024. All rights reserved.