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
My table name is a test, and for concatenation, I use the For XML Path ('') syntax. The stuff function inserts a string into another string. It deletes the specified length of characters in the first line at the starting position, and then inserts the second line into the first line at the starting position.
The STUFF functions are as follows: STUFF (character_expression, start, length, character_expression)
character_expression Is an expression of character data. character_expression can be a constant, a variable, or a column of character or binary data.
start Is an integer value indicating the location to start deleting and pasting. If the start or length is negative, a null string is returned. If the beginning is larger than the first character_expression expression, an empty string is returned. start may be of type bigint.
Length Is an integer specifying the number of characters to delete. If the length is greater than the first character_expression expression, deletion occurs before the last character in the last character expression. length can be bigint type.