将多行文本字段从多行分组到一列中

时间:2018-06-11 13:37:12

标签: sql sql-server sql-server-2008-r2

我有以下声明:

SELECT *
FROM 
    (
    SELECT 123 AS id, 123445 AS OrderNr, '775-1x, 775-1xx, 775-1xxx' AS Reference
    ) AS SUB

这就是结果的样子:

{{1}}

1 个答案:

答案 0 :(得分:1)

您似乎希望使用stuff()函数 xml 方法:

with sub as (
       SELECT 123 AS id, 123445 AS OrderNr, '775-1x' AS Reference
       UNION ALL
       SELECT 123 AS id, 123445 AS OrderNr, '775-1xx' AS Reference
       UNION ALL
       SELECT 123 AS id, 123445 AS OrderNr, '775-1xxx' AS Reference
)
select id, OrderNr,
       stuff( (select ','+Reference 
               from sub s1 
               where s1.id = s.id and s1.OrderNr = s.OrderNr
               for xml path('')
              ), 1, 1, ''
            ) as Reference
from sub s
group by id, OrderNr;