在MySQL和Oracle中实现行合并

在MySQL和Oracle中实现行合并
我有一个表student, 有id, name, email, 这时候我表里记录有name重复的值, 而email不一样, 我想按照name来group by一下, 把有重复的数据里面的email用逗号分开写在一起.
表结构以及数据如下:
id  name       email
1   eric         [email protected]
2   maggie    [email protected]
3   scott       [email protected]
4   eric         [email protected]
我想的到如下数据
eric           [email protected],[email protected]
maggie      [email protected]
scott         [email protected]

如果使用MySQL, 则实现语句如下:
select name , group_concat(email order by email separator ", ") as email from student group by name

如果以上效果想在Oracle中显示, 则比较复杂点了, 因为Oracle中没有行合并函数, 则需要使用sys_connect_by_path()来实现, 代码如下:
select name, ltrim(sys_connect_by_path(email,','),',') email from(
select name,email,
row_number() over(partition by name order by email) rn,
count(*) over(partition by name) cnt
from student
) where level = cnt
start with rn = 1
connect by prior name = name and prior rn + 1 = rn

你可能感兴趣的:(在MySQL和Oracle中实现行合并)