如何在Amazon Redshift的列中取消嵌套/分解/展平逗号分隔值?

时间:2019-05-22 17:39:04

标签: sql postgresql amazon-redshift amazon-rds amazon-redshift-spectrum

我正在尝试为col2中的每个值生成一个新行。由于该值是字符串格式,因此我需要在其上使用任何Redshift json函数之前将其用双引号引起来。

Input:=>
col1(int)       col2(varchar)
1               ab,cd,ef
2               gh
3               jk,lm,kn,ut,zx



Output:=>
col1(int)       col2(varchar)
1               ab
1               cd
1               ef
2               gh
3               jk
3               lm
3               kn
3               ut
3               zx

1 个答案:

答案 0 :(得分:0)

    with NS AS (
      select 1 as n union all
      select 2 union all
      select 3 union all
      select 4 union all
      select 5 union all
      select 6 union all
      select 7 union all
      select 8 union all
      select 9 union all
      select 10
    )
    select
      TRIM(SPLIT_PART(B.col2, ',', NS.n)) AS col2
    from NS
    inner join table B ON NS.n <= REGEXP_COUNT(B.col2, ',') + 1

在这里,NS(数字序列)是一个CTE,它返回从1到N的数字列表,这里我们必须确保我们的最大数字大于我们最大标签的大小,因此您可以尝试添加根据您的具体情况,列表中还会显示更多数字。