连接列并在数字后添加数字

问题描述 投票:1回答:1

给出PostgreSQL中的表table1

数字1 | number2 | min_length |最长长度40 | 1801 | 8 | 840 | 182 | 8 | 842 | 32 | 6 | 842 | 4 | 6 | 643 | 691 | 9 | 9

我想创建新表table2,例如:

开始停4018010000 | 40180199994018200000 | 401829999942320000 | 42329999423200000 | 4232999994232000000 | 423299999942400000 | 4249999943691000000 | 43691999999

因此新表将包含:

column_1 =串联的old_column_1 + old_column_2 +等于“ old”的数字“ 0”(old_column_3-old_column_2的长度)
column_2 =串联的old_column_1 + old_column_2 +等于“ old_column_3-old_column_2的长度”的数字“ 9”

并且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

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

sql postgresql concat generate-series set-returning-functions
1个回答
1
投票

假设所有列均为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 <>小提琴here

generate_series()generate_series()的手册。

如果rpad()rpad()可以是number1,则抛出number2

NULL

db <>小提琴COALESCE

如果COALESCESELECT 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; 可以是here,则必须定义应该发生的事情。

© www.soinside.com 2019 - 2024. All rights reserved.