在某些行变成列的同时,从两个表创建视图

时间:2019-02-03 00:59:03

标签: sql

嘿,我是sql的新手,我在fpdf上显示数据时遇到问题。我有这些下表:

tbl_students

studentID|fname |mname|lname   |grade  |section      |sy       |teacherid     
14-10546 |Aljhon|C    |Austria |Grade 2|St. Bernadeth|2018-2019|15-11100
12-23534 |Buklaw|K    |Buknoy  |Grade 2|St. Bernadeth|2018-2019|15-11100

tbl_grades

studentID|subjectID  |period        |sy       |final_grade
14-10546 |Science 101|First Grading |2018-2019|79.40       
14-10546 |Science 101|Second Grading|2018-2019|87.91
14-10546 |Science 101|Third Grading |2018-2019|0.00
14-10546 |Science 101|Fourth Grading|2018-2019|0.00
12-23534 |Science 101|First Grading |2018-2019|77.40       
12-23534 |Science 101|Second Grading|2018-2019|98.34        
12-23534 |Science 101|Third Grading |2018-2019|0.00
12-23534 |Science 101|Fourth Grading|2018-2019|0.00

我要这样创建视图view_all_grades

    studentID|fname |grade  |section      |sy       |FirstGrading|SecondGrading|ThirdGrading|FourthGrading    
    14-10546 |Aljhon|Grade 2|St. Bernadeth|2018-2019|79.40       |87.91        |0.00        |0.00            
    12-23534 |Buklaw|Grade 2|St. Bernadeth|2018-2019|77.40       |98.34        |0.00        |0.00        

到目前为止,我尝试执行命令后收到一些错误:

  

#1370-对例程'tbl_grades.max'的用户'legend63'@'localhost'执行拒绝的命令

CREATE view view_all_grades AS 
SELECT 
    tbl_students.studentID, 
    tbl_students.fname, 
    tbl_students.grade, 
    tbl_students.section, 
    tbl_students.sy, 
    tbl_grades.max(case when tbl_grades.period = 'First Grading' then tbl_grades.final_grade end) FirstGrading 
FROM 
    tbl_students 
    INNER JOIN tbl_grades ON tbl_students.studentID = tbl_grades.studentID

1 个答案:

答案 0 :(得分:0)

在SQL中,将数据遍历固定数量的列的通常方法是使用条件聚合

CREATE view view_all_grades AS
SELECT
    st.studentID,
    st.fname,
    st.grade,
    st.section,
    st.sy,
    gr.subjectID,
    MAX(CASE WHEN gr.period = 'First Grading'  THEN gr.final_grade END) FirstGrading,
    MAX(CASE WHEN gr.period = 'Second Grading' THEN gr.final_grade END) SecondGrading,
    MAX(CASE WHEN gr.period = 'Third Grading'  THEN gr.final_grade END) ThirdGrading,
    MAX(CASE WHEN gr.period = 'Fourth Grading' THEN gr.final_grade END) FourthGrading
FROM
    tbl_students st
    INNER JOIN tbl_grades gr ON gr.studentID = st.studentID
GROUP BY
    st.studentID,
    st.fname,
    st.grade,
    st.section,
    st.sy,
    gr.subjectID

PS:从查看您的样本数据来看,我怀疑您需要在视图中包括列subjectID(否则,当一个学生在多个学科中获得成绩时会发生什么?),因此我将其添加到查询的非聚合列中。