GROUP BY SQL中的一个字段,并将所有分组行的特定字段合并为一列[复制]

时间:2022-12-25 07:56:41

This question already has an answer here:

这个问题在这里已有答案:

I have a situation where I need to group SQL results by a specific field, while at the same time I need all values of a specific column of the grouped rows to be returned in one field (like so values1,value2,value3 etc)

我有一种情况需要按特定字段对SQL结果进行分组,同时我需要在一个字段中返回分组行的特定列的所有值(如value1,value2,value3等)

example data:

示例数据:

NAME id 
john 1
john 2
john 3
maria 4
maria 5

result I need:

结果我需要:

john 1,2,3
maria 4,5

Is this possible and how?

这可能吗?怎么样?

1 个解决方案

#1


0  

This is possible and here is the simple example of GROUP_CONCAT, You may get your desired output after run this/ execute this. The example is with a delimiter ', ' as well, so you can quick understand the things.

这是可能的,这是GROUP_CONCAT的简单示例,运行此/执行此操作后,您可以获得所需的输出。该示例也带有分隔符','因此您可以快速了解这些内容。

The GROUP_CONCAT function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values

GROUP_CONCAT函数返回一个字符串结果,其中包含来自组的连接非NULL值。如果没有非NULL值,则返回NULL

SELECT name,
    GROUP_CONCAT(DISTINCT id ORDER BY id DESC SEPARATOR ', ')
    FROM table_name
GROUP BY name;

This may help you.

这可能对你有所帮助。

#1


0  

This is possible and here is the simple example of GROUP_CONCAT, You may get your desired output after run this/ execute this. The example is with a delimiter ', ' as well, so you can quick understand the things.

这是可能的,这是GROUP_CONCAT的简单示例,运行此/执行此操作后,您可以获得所需的输出。该示例也带有分隔符','因此您可以快速了解这些内容。

The GROUP_CONCAT function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values

GROUP_CONCAT函数返回一个字符串结果,其中包含来自组的连接非NULL值。如果没有非NULL值,则返回NULL

SELECT name,
    GROUP_CONCAT(DISTINCT id ORDER BY id DESC SEPARATOR ', ')
    FROM table_name
GROUP BY name;

This may help you.

这可能对你有所帮助。