简体   繁体   中英

SQL: Combine Records with Same ReferenceID

I have the following records inside my table

ID   StudentID   Semester   Grade     
1    1           First      100
2    1           Second     90
3    2           First      90
4    1           Third      85

I want to combine all the records of Student ID 1 in one record

StudentID   First   Second   Third
1           100     90       85 
2           90      null     null

Any ideas?

Since you haven't mention what RDBMS you are using, try this one out.

SELECT  StudentID,
        MAX(CASE WHEN Semester = 'First' THEN Grade ELSE NULL END) AS First,
        MAX(CASE WHEN Semester = 'Second' THEN Grade ELSE NULL END) AS Second,
        MAX(CASE WHEN Semester = 'Third' THEN Grade ELSE NULL END) AS Third
FROM    tableName
GROUP BY StudentID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM