Select and merge rows in a table in SQL Stored procedure

前端 未结 3 1322
梦毁少年i
梦毁少年i 2021-01-28 01:40

Have a temp table with schema: ID | SeqNo | Name

ID - Not unique
SeqNo - Int (can be 1,2 or 3). Sort of ID+SeqNo as Primary key
Name - Any text

And sam

3条回答
  •  深忆病人
    2021-01-28 01:51

    If SeqNo is limited to 1,2,3:

    select id, a.name + coalesce('/'+b.name, '') + coalesce('/'+c.name, '')
    from myTable a
    left outer join myTable b on a.id=b.id and b.seqno = 2
    left outer join myTable c on a.id=c.id and c.seqno = 3
    where a.seqno = 1;
    

    If SeqNo is open ended you can deploy a recursive cte:

    ;with anchor as (
       select id, name, seqno
          from myTable
          where seqno=1)
    , recursive as (
       select id, name, seqno
          from anchor
          union all
       select t.id, r.name + '/' + t.name, t.seqno
          from myTable t
          join recursive  r on t.id = r.id and r.seqno+1 = t.seqno)
    select id, name from recursive;
    

提交回复
热议问题