mysqlsqlamazon-redshiftdenormalized

Convert comma delimited values in a column into rows


I would like to convert comma-delimited values into rows in Redshift

For example:

store  |location |products
-----------------------------
1      |New York |fruit, drinks, candy...

The desired output is:

store  |location | products
------------------------------- 
1      |New York | fruit        
1      |New York | drinks         
1      |New York | candy     

Are there any simple solution that I could split the words based on delimiters and convert into rows? I was looking into this solution but it does not work yet: https://help.looker.com/hc/en-us/articles/360024266693-Splitting-Strings-into-Rows-in-the-Absence-of-Table-Generating-Functions

Any suggestions would be greatly appreciated.


Solution

  • If you know the maximum number of values, I think you can split_part():

    select t.store, t.location, split_part(products, ',', n.n) as product
     from t join
          (select 1 as n union all
           select 2 union all
           select 3 union all
           select 4
          ) n
          on split_part(products, ',', n.n) <> '';
     
    

    You can also use:

    select t.store, t.location, split_part(products, ',', 1) as product
    from t 
    union all
    select t.store, t.location, split_part(products, ',', 2) as product
    from t 
    where split_part(products, ',', 2) <> ''
    union all
    select t.store, t.location, split_part(products, ',', 3) as product
    from t 
    where split_part(products, ',', 3) <> ''
    union all
    select t.store, t.location, split_part(products, ',', 4) as product
    from t 
    where split_part(products, ',', 4) <> ''
    union all
    . . .