有一张表,学生成绩表,如下。
现在要把语文,数学,英语提取出来作为字段,横向的显示。
SELECT
name,
SUM(
IF (course = '英语', score, 0)
) english,
SUM(
IF (course = '数学', score, 0)
) math,
sum(
IF (course = '语文', score, 0)
) chinese
FROM
score
GROUP BY name
ORDER BY id
扩展一下,增加两列:每个学生的总成绩,以及平均分(保留两位小数)。
SELECT
name,
SUM(
IF (course = '英语', score, 0)
) english,
SUM(
IF (course = '数学', score, 0)
) math,
sum(
IF (course = '语文', score, 0)
) chinese,
SUM(score) total_score,
ROUND(AVG(score), 2) avg_score
FROM
score
GROUP BY name
ORDER BY id