在table的每个字段和字段中的每个字符之间插入分隔符

Insert a delimiter between each field of a table and each character in a field

我有一个包含 4 个字段的 table - 姓名、年龄、性别、城市。以下是示例数据。

我需要将输出作为单个列获取,字段之间的值由“-”分隔,值中的字符由“-”分隔

输出:a-b-c-d-3-3-m-a-l-e-p-q-r

我尝试了以下仅分隔字段的查询。

select trim(case when name is not null then name||'-'end ||case when age is not null then age||'-' end ||
case when sex is not null then sex||'-'end || case when city is not null then city end) from table

有没有办法在每个字段中分隔值。

我正在使用 Teradata 16,但如果在任何其他 RDBMS 中同样可行,请提供帮助。

尝试

select
regexp_replace(name,'\B', '-')||'-'||
regexp_replace(age,'\B', '-')||'-'||
regexp_replace(sex,'\B', '-')||'-'||
regexp_replace(city,'\B', '-')
from table

请使用以下查询。您可以使用 WHERE 子句代替 case 语句。

select name||'-'||age||'-'||sex||'-'||city from table
where (trim(name) is not null or trim(age) is not null or trim(sex) is  not nll or 
trim(city) is not null);

或者简单地说,

select name||'-'||age||'-'||sex||'-'||city from table

先连接所有列,然后使用 RegEx 为每个字符附加破折号

regexp_replace(coalesce(name,'')||
               coalesce(trim(age),'')||
               coalesce(sex,'')||
               coalesce(city,'')
              ,'(?!^|$)'   -- match every character besides begin and end of line
              ,'-')      -- append dash to each match

这个解决方案有点复杂,但效果很好。

create or replace function splitjoin(records TEXT[]) returns TEXT[] as $$
declare
cursrow varchar(20) ;
output varchar(30) :='' ;
nums TEXT[] := ARRAY[]::TEXT[];
rec text;
 begin
        FOREACH rec IN ARRAY records LOOP
           FOR counter IN 1..length(rec) BY 1 LOOP
             output=output||'-'||substring(rec,counter,1);
           END LOOP;
         nums =array_append(nums,substring(output,2));
        output='';
      
       END LOOP;
      RETURN nums; 
      end ; $$
     language  plpgsql;

创建以上函数 然后 运行 以下 select 命令

select unnest( splitjoin( (select array(select name||age||sex||city :: text from table  )))::text[]);

您正在传递像 {abcd33malepqr,efgh11femaleabc} 这样的串联记录数组 并且函数的结果也是一个数组 {a-b-c-d-3-3-m-a-l-e-p-q-r,e-f-g-h-1-1-f-e-m-a-l-e-a-b-c} 所以在 select 中使用 unnest 返回记录作为

 a-b-c-d-3-3-m-a-l-e-p-q-r
 e-f-g-h-1-1-f-e-m-a-l-e-a-b-c