您的位置:首页 > 数据库

sql 查询科目成绩以及平均成绩

2016-10-08 18:49 344 查看
score表

stuid subject score

1 math 80

1 english 90

2 math 81

2 english 91

3 math 85

3 english 95

要求得到的组合查询结果

id math english sum

1 80 90 170

2 81 91 172

3 85 95 180

avg 82 92 174

(
SELECT
stuid as id,
CAST(sum(case when `subject`='math' then score end) AS SIGNED) as math,
CAST(sum(case when `subject`='english' then score end) AS SIGNED) as english,
CAST((
sum(case when `subject`='math' then score end)
+
sum(case when `subject`='english' then score end)
) AS SIGNED) as 'sum'
FROM
score
GROUP BY
stuid
)
UNION
(
SELECT
'avg' as id,
CAST(avg(case when `subject`='math' then score end) AS SIGNED) as math,
CAST(avg(case when `subject`='english' then score end) AS SIGNED) as english,
CAST((
avg(case when `subject`='math' then score end)
+
avg(case when `subject`='english' then score end)
) AS SIGNED) as 'sum'
FROM
score
)


union 对两个结果集进行并集操作,重复数据只显示一次

union All,对两个结果集进行并集操作,重复数据全部显示
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: