连接列并添加数字postgresql

Concatenate columns and adds digits postgresql

鉴于 PostgreSQL 中的 table table1:

number1 | number2 | min_length | max_length
40      |  1801   |     8      |     8  
40      |  182    |     8      |     8  
42      |  32     |     6      |     8  
42      |  4      |     6      |     6  
43      |  691    |     9      |     9  

我想创建新的 table table2 喜欢:

start        |      stop
4018010000   |      4018019999  
4018200000   |      4018299999  
42320000     |      42329999
423200000    |      423299999
4232000000   |      4232999999
42400000     |      42499999  
43691000000  |      43691999999  

所以新的 table 将包括:

column_1 = a concatenation of old_column_1 + old_column_2 + a number of "0" equal to (old_column_3 - length of the old_column_2)
column_2 = a concatenation of old_column_1 + old_column_2 + a number of "9" equal to (old_column_3 - length of the old_column_2) 

而当min_length不等于max_length时,我需要考虑所有可能的长度。所以对于行 "42";"32";6;8 ,所有长度都是:6,7 和 8.

我尝试创建新的 table2 AS table1,然后创建新的开始和停止列,然后像这样连接第 1 列和第 2 列:

create table table2 as select * from table1;
alter table table2 add column start text,
                   add column stop text;
update table2 set start = number1 || number2

用于连接前 2 列。但我不知道如何进行所有连接,添加“0"s and the "9”。

假设所有列都是 NOT NULL,并且 max_length 总是大于 min_length 这就是工作:

CREATE TABLE table2 AS
SELECT t.number1::text || rpad(t.number2::text, len, '0') AS start
     , t.number1::text || rpad(t.number2::text, len, '9') AS stop
FROM   table1 t, generate_series(min_length, max_length) len

db<>fiddle here

generate_series() and rpad().

的手册

如果number1number2可以是NULL,则抛出COALESCE

SELECT COALESCE(t.number1::text, '') || rpad(COALESCE(t.number2::text,''), len, '0') AS start
     , COALESCE(t.number1::text, '') || rpad(COALESCE(t.number2::text,''), len, '9') AS stop
FROM table1 t, generate_series(min_length, max_length) len;

db<>fiddle here

如果 min_lengthmax_length 可以是 NULL,您必须定义应该发生的情况。