合并列数据

时间:2018-07-10 22:04:50

标签: sql sql-server

SELECT Name, Members 
FROM People 
WHERE Name LIKE '%Kako%' 
GROUP BY Name, Members

我从上面显示的SQL查询中得到了这个结果:

Name        |   Members
------------+-------------
James Kako  |   Rangers
James Kako  |   Wind
James Kako  |   Poers
James Kako  |   Lohe
James Kako  |   Jubo
J. Kako     |   Wind
J. Kako     |   Lohe
J. Kako     |   Poers

我想像这样合并Members列:

Name        | Members
------------+---------------------------------
James Kako  | Rangers, Wind, Poers, Lohe, Jubo
J. Kako     | Wind, Lohe, Poers

提前谢谢

2 个答案:

答案 0 :(得分:1)

使用STRING_AGG是解决这类问题的直接方法:

SELECT Name, STRING_AGG(Members, ', ') as Members
  FROM People
 WHERE Name LIKE '%Kako%'
GROUP BY Name
ORDER BY Name DESC;

SQL Fiddle Demo

答案 1 :(得分:0)

此解决方案也可以正常工作:

DECLARE @char VARCHAR(MAX);
SELECT @char = COALESCE(@char + ', ' + members, members) 
FROM MergeColumn ;
Select name , @char as Mergerd from MergeColumn group by name;

此外,您可以查看此链接,以获取针对您所问问题的更多解决方案:How to concatenate text from multiple rows into a single text string in SQL server?