将连接的行转换为sql中的列

时间:2014-03-06 17:43:57

标签: sql

请帮助我想更改下表

StudentCode CourseCode  Year    term    ExamModel   score   School
102188452   1522            80  1      1            6.25    46622401
102188452   1522            80  1      2            10  46622401
102188452   1522            80  1      3             7  46622401
102188452   1522            80  1      4             5  46622401
102188452   1522            80  2      1             10 46622401
102188452   1525            80  1      1             6.5    46622401
102188452   1525            80  1      2             12 46622401
102188452   1525            80  1      3            13.75   46622401
102188452   1525            80  1      4             14 46622401
102188452   1525            80  2      1             10 46622401
102188452   5435            80  1      1             11 46622401
102188452   5435            80  1      2              8 46622401
102188452   5435            80  1      3             10 46622401
102188452   5435            80  1      4             13 46622401
102188452   7991            78  1      1             15 46620903
102188452   7991            78  1      3             19 46620903
102188452   7991            79  1      1             10 46622304
102188452   7991            79  1      3             17 46622304
102188452   7991            80  1      1             18 46622401
102188452   7991            80  1      3             17 46622401

我想要下表

Student        Course   Year   term    model1  model2 model3  model4     school
102188452           1522    80  1   6.25    10  7   5   46622401
102188452           1525    80  1   6.5 12  13.75   14  46622401
102188452           5435    80  1   11  8   10  13  46622401
102188452           7991    80  1   18  ….. 17  ……  46622401
102188452           1522    80  2   10  ….. ….. ….. 46622401
102188452           1525    80  2   10  ….. ….. ….. 46622401
102188452           7991    78  1   15  ….. 19  ….. 46620903
102188452           7991    79  1   10  ….. ….. ….. 46622304
102188452           7991    79  1   ….. ….. 17  ….. 46622304

2 个答案:

答案 0 :(得分:0)

尝试以下

SELECT StudentCode, CourseCode,  Year, term,  
SUM(case when ExamModel = 1 then score else 0 end) 'model1',
SUM(case when ExamModel = 2 then score else 0 end) 'model2',
SUM(case when ExamModel = 3 then score else 0 end) 'model3',
SUM(case when ExamModel = 4 then score else 0 end) 'model4',
,School
FROM your_table
GROUP BY StudentCode, CourseCode,  Year, term, School

答案 1 :(得分:0)

使用CASE将行映射到列,然后使用
使用GROUP BY以1行显示所有4个映射列:

SELECT StudentCode, CourseCode,  Year, term,  
    MAX(CASE WHEN ExamModel = 1 THEN score END) AS 'model1',
    MAX(CASE WHEN ExamModel = 2 THEN score END) AS 'model2',
    MAX(CASE WHEN ExamModel = 3 THEN score END) AS 'model3',
    MAX(CASE WHEN ExamModel = 4 THEN score END) AS 'model4',
    School
FROM T
GROUP BY StudentCode, CourseCode,  Year, term, School

see example in SQL Fiddle