T-SQL - Group By Select join String?

时间:2017-12-17 04:30:59

标签: sql-server tsql group-by

是否可以在T-SQL

中将组字符串名称添加到分组集中
Name     |    NO      |  
---------+------------+ 
A        |      1     |
B        |      1     |
C        |      1     |
E        |      2     |
F        |      2     |
G        |      2     |

输出名称以字符串形式连接。

Name     |    NO      |  
---------+------------+ 
A,B,C    |     1      | 
E,F,G    |     2      |

Declare @tbG Table(idx  int , Name  nvarchar(250))
Insert into @tbG values (1,'A'),(1,'B'),(1,'C'),(2,'E'),(2,'F'),(2,'G');

SELECT Name, idx AS column_names
FROM @tbG AS extern
CROSS APPLY
(
    SELECT Name + ','
    FROM @tbG AS intern
    WHERE extern.idx = intern.idx
    FOR XML PATH('')
) pre_trimmed (column_names)
GROUP BY idx, Name; 

我认为以下是我的解决方案,但我无法取代示例。

SELECT table_name, LEFT(column_names , LEN(column_names )-1) AS column_names
FROM information_schema.columns AS extern
CROSS APPLY
(
    SELECT column_name + ','
    FROM information_schema.columns AS intern
    WHERE extern.table_name = intern.table_name
    FOR XML PATH('')
) pre_trimmed (column_names)
GROUP BY table_name, column_names;

0 个答案:

没有答案