首页 > 数据库 > mysql教程 > MySQL – Grouping by Multiple Columns to Single Column as A_MySQL

MySQL – Grouping by Multiple Columns to Single Column as A_MySQL

WBOY
发布: 2016-06-01 13:14:37
原创
1169 人浏览过

In this post titledSQL SERVER – Grouping by Multiple Columns to Single Column as A Stringwe have seen how to group multiple column data in comma separate values in a single row grouping by another column by using FOR XML clause.

In this post we will see how we can produce the same result usingthe GROUP_CONCAT functionin MySQL.

Let us create the following table and data.

CREATE TABLE TestTable (ID INT, Col VARCHAR(4));<br> INSERT INTO TestTable (ID, Col)<br> SELECT 1, 'A'<br> UNION ALL<br> SELECT 1, 'B'<br> UNION ALL<br> SELECT 1, 'C'<br> UNION ALL<br> SELECT 2, 'A'<br> UNION ALL<br> SELECT 2, 'B'<br> UNION ALL<br> SELECT 2, 'C'<br> UNION ALL<br> SELECT 2, 'D'<br> UNION ALL<br> SELECT 2, 'E';<br>

Now to generatecsvvalues of the column col for each ID, use the following code

SELECT ID, GROUP_CONCAT(col) AS CSV FROM TestTable<br> GROUP BY ID;

The result is

ID CSV 1 A,B,C 2 A,B,C,D,E
登录后复制

You can also change the delimiters. Forexample insteadof comma, if you want to have a pipe symbol (|), use the following

SELECT ID, REPLACE(GROUP_CONCAT(col),',','|') AS CSV FROM TestTable<br> GROUP BY ID;

The result is

ID CSV 1 A|B|C 2 A|B|C|D|E
登录后复制

MySQL makes this very simple withitssupport of GROUP_CONCAT function.

Reference: Pinal Dave (http://blog.sqlauthority.com)

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板