连接列并添加数字postgresql

zpf6vheq  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(287)

把table给我 table1 在postgresql中:

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

我要创建新表 table2 比如:

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

因此,新表将包括:

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创建为table1,然后创建新的列start和stop,然后像这样连接列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

用于前两列的串联。但我不知道如何进行所有连接,添加“0”和“9”。

5jdjgkvh

5jdjgkvh1#

假设所有列都是 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<>在这里摆弄
手册 generate_series() 以及 rpad() .
如果 number1 或者 number2 可以是 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<>在这里摆弄
如果 min_length 或者 max_length 可以是 NULL ,你必须定义应该发生什么。

相关问题