标签:
先根据如下语句生成测试表并填充数据
CREATE TABLE z ( a INT, b INT); INSERT INTO Z SELECT 1,200; INSERT INTO Z SELECT 1,100; INSERT INTO Z SELECT 1,100; INSERT INTO Z SELECT 2,400; INSERT INTO Z SELECT 2,500; INSERT INTO Z SELECT 3,NULL;
SELECT a, GROUP_CONCAT(b) FROM z GROUP BY a;
GROUP_CONCAT([DISTINCT] expr [,expr ...] [ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [,col_name ...]] [SEPARATOR str_val])
DISTINCT选项可以去除重复值,ORDER选择可以对列进行排序,SEPARATOR用于选择拼接的字符串。例如上述例子中,可以对b列进行去重并按递减的顺序排序,同时用“:”拼接字符串。其SQL语句可写为:
SELECT a,GROUP_CONCAT(DISTINCT b ORDER BY b DESC SEPARATOR ‘:‘) FROM z GROUP BY a;
运行结果如下图
标签:
原文地址:http://www.cnblogs.com/chenqionghe/p/4679725.html