数据库多行数据合并一行(sqlserver、Oracle、Mysql)

以下分别总结了sqlserver、Oracle、MySQL数据的处理SQL:

1.sqlserver:

SELECT
    username,
    coursename= (
               STUFF(
                    (SELECT ',' + coursename
                     FROM t_user_course
                     WHERE username= A.username
                     FOR xml path('')
                    ),1,1,''
                    )
                 )
FROM t_user_course A
GROUP by cm_pk1;

2.Oracle

(适用于oracle 12c以下版本)
select username,wm_concat(to_char(coursename)) from t_user_course group by username;
(适用于oracle 12c以上版本)
select username, id, LISTAGG(subject, '-') within group(order by subject) as subject, LISTAGG(score, ',') within group(order by score) as score
from STUDENTSCORES
group by username, id

3.Mysql

select username,group_concat(coursename Separator ',') as coursename from t_user_course group by username;

推荐阅读更多精彩内容