将多行中的多个文本字段分组到一列中
GROUP multiple text fields from multiple rows into one column
我有以下声明:
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
你似乎想要 xml 方法和 stuff()
函数 :
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;
我有以下声明:
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
你似乎想要 xml 方法和 stuff()
函数 :
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;