我需要选择多个表,其中一个是转置的,我的表格如下:
table_score
|ID | Subject | Score|
----------------------
|001 | 2GSLIG | 80 |
|001 | 3ECITI | 70 |
|002 | 2GSLIG | 75 |
|002 | 3ECITI | 85 |
-----------------------
table_student
|ID | StudentName |
--------------------
|001 | Diana |
|002 | Yose |
--------------------
然后我想进入
|ID |StudentName| 2GSLIG | 3ECITI |
-----------------------------------
|001| Diana | 80 | 70 |
|002| Yose | 85 | 75 |
----------------------------------
这是我的代码到目前为止,但我遇到错误
SELECT (
ID,
SUM(IF(Subject = '2GSLIG', Score, 0)) AS `2GSLIG`,
SUM(IF(Subject = '3ECITI', Score, 0)) AS `3ECITI`
FROM table_score) JOIN (SELECT StudentName from table_student)
GROUP BY ID
我想知道是否有人会帮助我,谢谢
答案 0 :(得分:1)
SELECT tsc.ID,
tst.StudentName,
SUM(CASE WHEN tsc.Subject='2GSLIG' THEN tsc.Score END) AS '2GSLIG',
SUM(CASE WHEN tsc.Subject='3ECITI' THEN tsc.Score END) AS '3ECITI'
FROM table_score tsc
INNER JOIN
table_student tst
ON tsc.ID = tst.ID
GROUP BY tsc.ID,tst.StudentName;
在SQLFIDDLE上查看 - http://sqlfiddle.com/#!3/68e96/1
答案 1 :(得分:1)
select st.ID,
st.StudentName,
SUM(case when sc.Subject = '2GSLIG' then sc.Score end) as `2GSLIG`,
SUM(case when sc.Subject = '3ECITI' then sc.Score end) as `3ECITI`
from table_score sc
join table_student st on sc.ID = st.ID
group by st.ID,
st.StudentName