首页 > 解决方案 > 在表格的每个字段和字段中的每个字符之间插入分隔符

问题描述

我有一个包含 4 个字段的表格 - 姓名、年龄、性别、城市。下面是样本数据。

在此处输入图像描述

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

输出:abcd-3-3-malepqr

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

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 中也可以使用,请提供帮助。

标签: sqlteradata

解决方案


首先连接所有列,然后使用正则表达式将破折号附加到每个字符

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

推荐阅读