IF OBJECT_ID('master..test') is not null Drop table test
CREATE TABLE test (ID INTEGER, NAME VARCHAR (50), VALUE INTEGER );
INSERT INTO test VALUES (1, 'A', 4);
INSERT INTO test VALUES (1, 'A', 5);
INSERT INTO test VALUES (1, 'B', 8);
INSERT INTO test VALUES (2, 'C', 9);
select distinct NAME , LIST = Replace(Replace(Stuff((select ',', +Value from test where name = _a.name for xml path('')), 1,1,''),'<Value>', ''),'</Value>','') from test _a order by 1 desc
我的表名是 test ,对于连接,我使用 For XML Path('') 语法。
stuff 函数将一个字符串插入到另一个字符串中。它删除指定长度的字符
在开始位置的第一个字符串中,然后将第二个字符串插入到第一个字符串中
在起始位置。
STUFF 函数如下所示:STUFF (character_expression , start , length ,character_expression )
字符表达式
是字符数据的表达式。 character_expression 可以是常量、变量或列
字符或二进制数据。
开始
是一个整数值,指定开始删除和插入的位置。如果 start 或 length 为负数,
返回一个空字符串。如果 start 比第一个 character_expression 长,则返回一个空字符串。
start 可以是 bigint 类型。
长度
是一个整数,指定要删除的字符数。如果长度比第一个 character_expression 长,
删除直到最后一个 character_expression 中的最后一个字符。 length 可以是 bigint 类型。