SQL - columns for different categories

后端 未结 6 656
予麋鹿
予麋鹿 2020-12-09 11:39

I am new to SQL. I have a database with data for different exams, for example:

Student Test Grade
--------------------
St1    T1   A
St2    T1   B
St3    T1          


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 12:18

    There are a couple of ways to do it, both of which (in pure SQL and not code generating a SQL command) require the number of columns to be known and fixed. The most straightforward to implement would be:

    SELECT eg.Student,
    (SELECT Grade from ExamGrade eg1 WHERE eg1.Student = eg.Student AND Test = 'T1') AS T1
    (SELECT Grade from ExamGrade eg2 WHERE eg2.Student = eg.Student AND Test = 'T2') AS T2
    (SELECT Grade from ExamGrade eg3 WHERE eg3.Student = eg.Student AND Test = 'T3') AS T3
    FROM ExamGrade eg
    

    This will work in practically any environment including SQLite, and it could be made a bit more elegant with a scalar-valued function GetTest() that would take the student and test number and return the grade. However, in any case, this is neither performant nor closed to change; it will query the table N-squared times for N tests, and if you add a 4th test, this query will have to change to include it in the report.

    If the combination of Student and Test is unique, and you're working in a database with Pivot functionality (which apparently SQLite doesn't have), you can use a Pivot query with just about any aggregator (the MAX/MIN/AVG/SUM of a set with a single value is that value). The following works in MSS2005:

    SELECT Student, T1, T2, T3
    FROM (Select Student, Test, Grade FROM ExamGrade) As SourceQuery
    PIVOT (MAX(Grade) FOR Test IN (T1, T2, T3)) AS PivotTable
    

    This will be more performant, and it's far more elegant. The column lists still cannot be dynamically determined AFAIK, but they're trivial to generate if you're making this query from application code, or using the sp_executesql built-in stored proc in MS SQL Server to generate a query from another stored proc or function.

提交回复
热议问题