下面是一段示例代码:
SELECT s.name AS '姓名', c.name AS '课程', sc.score AS '成绩' FROM scores AS sc LEFT JOIN students AS s ON sc.sid = s.id LEFT JOIN courses AS c ON sc.cid = c.id ORDER BY s.name, c.name;
上面的代码中,大家从三个表(students、courses、scores)中获取了学生的姓名、课程名称和成绩信息,其中,students 表记录了学生的信息,courses 表记录了所有课程的信息,scores 表则记录了学生的成绩。
根据上面的代码,大家可以在查询结果中增加一个课程列,方法如下:
SELECT s.name AS '姓名', MAX(CASE WHEN c.id = 1 THEN sc.score ELSE NULL END) AS '语文', MAX(CASE WHEN c.id = 2 THEN sc.score ELSE NULL END) AS '数学', MAX(CASE WHEN c.id = 3 THEN sc.score ELSE NULL END) AS '英语' FROM scores AS sc LEFT JOIN students AS s ON sc.sid = s.id LEFT JOIN courses AS c ON sc.cid = c.id GROUP BY s.name ORDER BY s.name;
这段代码中,大家首先使用了三个 MAX(CASE WHEN THEN) 结构,根据课程编号(c.id)来判断成绩,从而获取每个学生在每个课程上的成绩。然后,大家使用 GROUP BY 语句按照学生姓名进行分组,得到按照姓名分类后的学生成绩。最后,使用 ORDER BY 语句让结果按学生姓名排序。
通过上述操作,在查询结果中增加了按课程分类的列,使得数据更加直观明了。