【问题标题】:Concatenate rows based on date in teradata根据 teradata 中的日期连接行
【发布时间】:2021-03-16 02:34:21
【问题描述】:

我有一个示例表如下:

Date   Type    String  Desired output

01/01   orange  aa      aa
01/10   orange  ab      aa,ab
02/01   orange  bb      aa,ab,bb
02/05   orange  ba      aa,ab,bb,ba
03/15   orange  cc      aa,ab,bb,ba,cc
02/11   apple   aa      aa

所以现在'Date','Type','String'列是已知的,我想返回所需的输出。我现在可以考虑的可能方法是使用连接函数并尝试了一种方法如下:

select
    t.*,
    row_number()over(partition by Type order by date) as rn,
    lag(string)over(partition by type order by date) as prev_string,
    case when rn = 1 then string when rn = 2 then concat(prev_string, ',', string) end as desired_output
from
    table as t

但是,通过使用上面的代码,它只能在 row_number =2 时返回。如何尝试根据先前的输出附加下一个字符串?我不知道如何解决这部分,并希望获得帮助。如果您能提供其他想法,我将不胜感激!

感谢您的帮助

【问题讨论】:

    标签: sql concatenation teradata


    【解决方案1】:

    我知道在 teradata 中执行此操作的唯一方法是使用递归 CTE。

    --base data
    create volatile table vt_foo 
    (dt date,
    typ varchar(10),
    val varchar(10)
    )
    
    on commit preserve rows;
    
    insert into vt_foo values ('2021-01-01','orange','aa');
    insert into vt_foo values ('2021-01-10','orange','ab');
    insert into vt_foo values ('2021-02-01','orange','bb');
    insert into vt_foo values ('2021-02-05','orange','ba');
    insert into vt_foo values ('2021-03-15','orange','cc');
    insert into vt_foo values ('2021-02-11','apple','aa');
    
    --add row number
    create volatile table vt_two as ( select
    t.*,
        row_number()over(partition by typ order by dt) as rn
    from
        vt_foo as t
    ) with data
    on commit preserve rows;
    
    
    with  recursive cte (rn , dt ,typ,val, concat_val) as (
    select
    rn,
    dt,
    typ,
    val,
    val as concat_val
    from
    vt_two
    where rn = 1
    UNION ALL
    select
    a.rn,
    a.dt,
    a.typ,
    a.val,
    b.concat_val || ',' || a.val
    from
    vt_two a
    inner join cte b
        on a.typ = b.typ
        and a.rn = b.rn + 1
    )
    
    select * from cte
    
    order by typ, dt
    ;
    

    【讨论】:

    • 你好安德鲁,谢谢!我也有类似的解决方案,稍后也会发布!谢谢!!
    猜你喜欢
    • 2020-02-17
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    相关资源
    最近更新 更多