How to use GROUP BY to concatenate strings in SQL Server?

前端 未结 20 2510
无人及你
无人及你 2020-11-21 04:33

How do I get:

id       Name       Value
1          A          4
1          B          8
2          C          9

to

id               


        
20条回答
  •  温柔的废话
    2020-11-21 04:57

    Another option using Sql Server 2005 and above

    ---- test data
    declare @t table (OUTPUTID int, SCHME varchar(10), DESCR varchar(10))
    insert @t select 1125439       ,'CKT','Approved'
    insert @t select 1125439       ,'RENO','Approved'
    insert @t select 1134691       ,'CKT','Approved'
    insert @t select 1134691       ,'RENO','Approved'
    insert @t select 1134691       ,'pn','Approved'
    
    ---- actual query
    ;with cte(outputid,combined,rn)
    as
    (
      select outputid, SCHME + ' ('+DESCR+')', rn=ROW_NUMBER() over (PARTITION by outputid order by schme, descr)
      from @t
    )
    ,cte2(outputid,finalstatus,rn)
    as
    (
    select OUTPUTID, convert(varchar(max),combined), 1 from cte where rn=1
    union all
    select cte2.outputid, convert(varchar(max),cte2.finalstatus+', '+cte.combined), cte2.rn+1
    from cte2
    inner join cte on cte.OUTPUTID = cte2.outputid and cte.rn=cte2.rn+1
    )
    select outputid, MAX(finalstatus) from cte2 group by outputid
    

提交回复
热议问题