根据B列的值连接A列 - SQL Server

时间:2016-06-22 17:06:15

标签: sql-server tsql sql-server-2012

I have a table that looks like the following


COLUMN_A|| COLUMN_B ||
======================
NAME1   ||    1     ||
NAME2   ||    1     ||
NAME3   ||    1     ||  
NAME4   ||    2     ||  
NAME5   ||    2     ||  
NAME6   ||    3     ||
NAME7   ||    3     ||  

我想根据COLUMN_B连接COLUMN_A。 如果COLUMN_B的值相同,则COLUMN_A应以逗号分隔连接。

预期结果

NAME1, NAME2, NAME3
NAME4, NAME5
NAME6, NAME7

2 个答案:

答案 0 :(得分:0)

Declare @Table table (id int,Name varchar(25))
Insert Into @Table values 
(1,'NAME1'),
(1,'NAME2'),
(1,'NAME3'),
(2,'NAME4'),
(2,'NAME5'),
(3,'NAME6'),
(3,'NAME7')



SELECT 
  [ID],
  STUFF((
    SELECT ', ' + NAME 
    FROM @Table
    WHERE (ID = Results.ID) 
    FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
  ,1,2,'') AS NAME
FROM @Table Results
GROUP BY ID

返回

ID  NAME
1   NAME1, NAME2, NAME3
2   NAME4, NAME5
3   NAME6, NAME7

答案 1 :(得分:0)

您可以使用递归来帮助解决此问题:

... $ dungeon ++ [Tile ...]