多行數(shù)據(jù)合并為一行數(shù)據(jù)
更新時(shí)間:
本文為您介紹,如何使用SQL實(shí)現(xiàn)多行數(shù)據(jù)合并為一行數(shù)據(jù)。
示例數(shù)據(jù)
class | gender | name |
1 | M | LiLei |
1 | F | HanMM |
1 | M | Jim |
1 | F | HanMM |
2 | F | Kate |
2 | M | Peter |
使用示例
示例1:將class相同的name合并為一行,并對(duì)name去重。去重操作可通過(guò)嵌套子查詢實(shí)現(xiàn)。
SELECT class, wm_concat(distinct ',', name) as names FROM students GROUP BY class;
說(shuō)明wm_concat
是字符拼接函數(shù),詳情請(qǐng)參見(jiàn)WM_CONCAT。輸出結(jié)果如下。
class
names
1
LiLei,HanMM,Jim
2
Kate,Peter
示例2:統(tǒng)計(jì)不同class對(duì)應(yīng)的男女人數(shù)。
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;
輸出結(jié)果如下。
class
cnt_m
cnt_f
1
2
2
2
1
1
文檔內(nèi)容是否對(duì)您有幫助?