SQL把ID相同的记录合并成同一条记录
SQL把ID相同的记录合并成同一条记录.需SQL 2005及以上.
Code
DECLARE @Table TABLE(id int, value varchar(10))
INSERT @Table SELECT 1, 'AA'
UNION ALL SELECT 1, 'BB'
UNION ALL SELECT 2, 'AAA'
UNION ALL SELECT 2, 'BBB'
UNION ALL SELECT 2, 'CCC'
UNION ALL SELECT 3, 'AAAA'
UNION ALL SELECT 3, 'BBBB'
UNION ALL SELECT 3, 'XXXX'
SELECT * FROM(
SELECT DISTINCT
id
FROM @Table
) A
OUTER APPLY(
SELECT
[values]= STUFF(REPLACE(REPLACE(
(
SELECT value FROM @Table N
WHERE id = A.id
FOR XML AUTO
), '<N value="', ','), '"/>', ''), 1, 1, '')
) N
DECLARE @Table TABLE(id int, value varchar(10))
INSERT @Table SELECT 1, 'AA'
UNION ALL SELECT 1, 'BB'
UNION ALL SELECT 2, 'AAA'
UNION ALL SELECT 2, 'BBB'
UNION ALL SELECT 2, 'CCC'
UNION ALL SELECT 3, 'AAAA'
UNION ALL SELECT 3, 'BBBB'
UNION ALL SELECT 3, 'XXXX'
SELECT * FROM(
SELECT DISTINCT
id
FROM @Table
) A
OUTER APPLY(
SELECT
[values]= STUFF(REPLACE(REPLACE(
(
SELECT value FROM @Table N
WHERE id = A.id
FOR XML AUTO
), '<N value="', ','), '"/>', ''), 1, 1, '')
) N