将多行中的多个文本字段分组为一列[重复]
Posted
技术标签:
【中文标题】将多行中的多个文本字段分组为一列[重复]【英文标题】:GROUP multiple text fields from multiple rows into one column [duplicate] 【发布时间】:2018-06-11 13:37:12 【问题描述】:我有如下声明:
SELECT *
FROM
(
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
) AS SUB
结果应该是这样的:
SELECT *
FROM
(
SELECT 123 AS id, 123445 AS OrderNr, '775-1x, 775-1xx, 775-1xxx' AS Reference
) AS SUB
【问题讨论】:
请包括您希望结果的显示方式。这将有助于确保我们理解您的问题。 【参考方案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;
【讨论】:
以上是关于将多行中的多个文本字段分组为一列[重复]的主要内容,如果未能解决你的问题,请参考以下文章