本文为您介绍,如何使用SQL实现多行数据合并为一行数据。
示例数据
class | gender | name |
1 | M | LiLei |
1 | F | HanMM |
1 | M | Jim |
1 | F | HanMM |
2 | F | Kate |
2 | M | Peter |
使用示例
示例1:将class相同的name合并为一行,并对name去重。去重操作可通过嵌套子查询实现。
SELECT class, wm_concat(distinct ',', name) as names FROM students GROUP BY class;
说明wm_concat
是字符拼接函数,详情请参见WM_CONCAT。输出结果如下。
class
names
1
LiLei,HanMM,Jim
2
Kate,Peter
示例2:统计不同class对应的男女人数。
SELECT class ,SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0 END) AS cnt_m ,SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END) AS cnt_f FROM students GROUP BY class;
输出结果如下。
class
cnt_m
cnt_f
1
2
2
2
1
1