SQL Server含GROUP BY子句的查询实现行值转列拼接的方法
实现方案
我们只需按Student_Id分组后对同组的分数做逗号分隔的字符串拼接即可,以下是各主流数据库的实现语句,均满足强制使用GROUP BY的要求:
MySQL 实现
SELECT Student_Id, GROUP_CONCAT(Student_Mark SEPARATOR ',') AS Student_Mark FROM Student_Marks GROUP BY Student_Id;
如果需要指定分数的拼接顺序,可以在GROUP_CONCAT中增加排序逻辑,例如按分数从高到低拼接:
SELECT Student_Id, GROUP_CONCAT(Student_Mark ORDER BY Student_Mark DESC SEPARATOR ',') AS Student_Mark FROM Student_Marks GROUP BY Student_Id;
SQL Server 2017及以上版本实现
SELECT Student_Id, STRING_AGG(Student_Mark, ',') AS Student_Mark FROM Student_Marks GROUP BY Student_Id;
Oracle 11gR2及以上版本实现
SELECT Student_Id, LISTAGG(Student_Mark, ',') WITHIN GROUP (ORDER BY NULL) AS Student_Mark FROM Student_Marks GROUP BY Student_Id;
PostgreSQL 实现
SELECT Student_Id, STRING_AGG(Student_Mark::VARCHAR, ',') AS Student_Mark FROM Student_Marks GROUP BY Student_Id;
内容的提问来源于stack exchange,提问作者Ram
相关产品推荐
相关产品推荐

