sql 查詢科目成績以及平均成績
阿新 • • 發佈:2018-12-25
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,對兩個結果集進行並集操作,重複資料全部顯示