How to use GROUP_CONCAT in a CONCAT in MySQL

前端 未结 7 1990
旧巷少年郎
旧巷少年郎 2020-11-22 11:38

If I have a table with the following data in MySQL:

id       Name       Value
1          A          4
1          A          5
1          B          8
2               


        
7条回答
  •  被撕碎了的回忆
    2020-11-22 11:52

    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,''),'', ''),'','') from test _a order by 1 desc
    

    My table name is test , and for concatination I use the For XML Path('') syntax. The stuff function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.

    STUFF functions looks like this : STUFF (character_expression , start , length ,character_expression )

    character_expression Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.

    start Is an integer value that specifies the location to start deletion and insertion. If start or length is negative, a null string is returned. If start is longer than the first character_expression, a null string is returned. start can be of type bigint.

    length Is an integer that specifies the number of characters to delete. If length is longer than the first character_expression, deletion occurs up to the last character in the last character_expression. length can be of type bigint.

提交回复
热议问题