How to get substring for filter and group by clause in AWS Redshift database

后端 未结 3 741
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-28 07:29

How to get substring from column which contains records for filter and group by clause in AWS Redshift database.

I have table with records like:

Table_Id         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-28 08:15

    If you have at most 3 values in any "categories" cell you can unnest the cells, get the list of unique values and use that list in a join condition like this:

    WITH
    values as (
        select distinct category
        from (
                select distinct split_part(categories,';',1) as category from your_table
                union select distinct split_part(categories,';',2) from your_table
                union select distinct split_part(categories,';',3) from your_table
         )
         where nullif(category,'') is not null
    )
    SELECT
     t2.category
    ,sum(t1.value)
    FROM your_table t1
    JOIN values t2
    ON split_part(categories,';',1)=t2.category
    OR split_part(categories,';',2)=t2.category
    OR split_part(categories,';',3)=t2.category
    

    if you have more than 3 options just add another split_part level both in WITH part and the join condition

提交回复
热议问题