【问题标题】:Concatenate columns and adds digits postgresql连接列并添加数字 postgresql
【发布时间】:2020-09-05 18:04:46
【问题描述】:

给定 PostgreSQL 中的表 table1:

编号1 |编号2 |最小长度 |最长长度 40 | 1801 | 8 | 8 40 | 182 | 8 | 8 42 | 32 | 6 | 8 42 | 4 | 6 | 6 43 | 691 | 9 | 9

我想创建新表table2 喜欢:

开始 |停止 4018010000 | 4018019999 4018200000 | 4018299999 42320000 | 42329999 423200000 | 423299999 4232000000 | 4232999999 42400000 | 42499999 43691000000 | 43691999999

所以新表将包括:

column_1 = old_column_1 + old_column_2 + 等于 (old_column_3 - old_column_2 的长度) 的数字“0”的串联 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,然后创建新列 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

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

【问题讨论】:

    标签: sql postgresql concat generate-series set-returning-functions


    【解决方案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() 和 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小提琴here

    如果min_length 或max_length 可以是NULL,您必须定义应该发生的事情。

    【讨论】:

    • 谢谢。但我确实有一些为空的字段。例如,如果我在“number2”列上有一个空字段,则表 2 中不会处理这种情况,我将丢失该特定字段的数据。这种情况有什么解决办法吗?
    • @Savas31:这就是为什么您应该在问题中使用表格定义。用COALESCE修复。
    • thnks,我试过 CREATE TABLE table3 AS SELECT t.number1::text || rpad(COALESCE(t.number2::text,''), len, '0') 作为开始,t.number1::text || rpad(COALESCE(t.number2::text,''), len, '9') AS stop FROM table1 t , generate_series(min_length, max_length) len;但结果是一样的。
    猜你喜欢
    • 2020-09-01
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 2011-01-26
    • 2013-09-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多