如何将行显示为列

时间:2019-05-24 10:02:20

标签: tsql pivot

例如,我想返回数据以将行显示为列;

ref, description
123, bananas, apples, oranges etc

可能有多个描述项。

表中的列表显示在表行中。

ref, description
123, bananas
123, apples
123, oranges

赞赏任何想法/代码。

这里是我创建的CTE,但很高兴探索其他强大的解决方案。

with PivotV as (


SELECT        [CO-PERSON-VULNERABILITY].person_ref [Ref], 
(case 
when [CO_VULNERABLE-CODES].DESCRIPTION = 'Restricted Mobility' then 'RM'
when [CO_VULNERABLE-CODES].DESCRIPTION = 'Progressive or Long Term Illness' then 'PLTI'
when [CO_VULNERABLE-CODES].DESCRIPTION = 'ASB / Injunction Order' then 'AIO'
when [CO_VULNERABLE-CODES].DESCRIPTION = 'Beware possible Drug Paraphernalia' then 'BPDP'
when [CO_VULNERABLE-CODES].DESCRIPTION = '[Can''t] Manage Stairs' then 'CMS'


else NULL end) as [VunDesc]
--,[CO-PERSON-VULNERABILITY].vulnerable_code, [CO_VULNERABLE-CODES].[VULNERABLE-IND], 

FROM            [CO-PERSON-VULNERABILITY] INNER JOIN
                         [CO_VULNERABLE-CODES] ON [CO-PERSON-VULNERABILITY].vulnerable_code = [CO_VULNERABLE-CODES].[VULNERABLE-IND])

1 个答案:

答案 0 :(得分:0)

不幸的是,在SQL Server 2017(您可以使用STRING_AGG())之前,做所需的事情并不容易。

SELECT t1.ref
     , STUFF((
       SELECT ',' + t2.description
         FROM #t as t2
        WHERE t2.ref = t1.ref
        ORDER BY t2.description
          FOR XML PATH('')), 1, LEN(','), '') as description
  FROM #t as t1
 GROUP BY t1.ref