SQL Server : Pivot Multiple Aggregates

前端 未结 1 1350
生来不讨喜
生来不讨喜 2021-01-25 02:39

I have been looking for an answer for a few hours about my problem.

My current table:

StudentName Course  Correct Wrong   Blank   Score
-----------------         


        
相关标签:
1条回答
  • 2021-01-25 03:15

    You can achieve this with a 'double pivot' by adding a new unique column for each subject/score combination before pivoting.

    Here's a static example, you can easily turn this into a dynamic pivot to cater for more classes. You could also put your original query in a CTE, insert into a temp table or inline as required - I've used a single temp table for clarity.

    Hope this helps.

    --Test Data 
    SELECT * INTO #Students FROM (VALUES
    ('Student1','Math',    38,      2,       0,       95),
    ('Student1','English', 45,      5,       0,       90),
    ('Student2','Math',    38,      2,       0,       95),
    ('Student2','English', 45,      5,       0,       90)
    ) A (StudentName, CourseName, Correct, Blank, Wrong, Score)
    
    --Pivoting
    SELECT StudentName
          ,SUM(Math_Correct) Math_Correct
          ,SUM(Math_Blank) Math_Blank
          ,SUM(Math_Wrong) Math_Wrong
          ,SUM(Math_Score) Math_Score
          ,SUM(English_Correct) English_Correct
          ,SUM(English_Blank) English_Blank
          ,SUM(English_Wrong) English_Wrong
          ,SUM(English_Score) English_Score
     FROM 
        (SELECT 
            S.StudentName
            ,S.CourseName+'_Correct' CourseNameCorrrect
            ,S.CourseName+'_Blank' CourseNameBlank
            ,S.CourseName+'_Wrong' CourseNameWrong
            ,S.CourseName+'_Score' CourseNameScore
            ,S.Correct
            ,S.Blank
            ,S.Wrong
            ,S.Score    
         FROM #Students S ) S2
        PIVOT( MAX(Correct) FOR CourseNameCorrrect IN ([Math_Correct], [English_Correct])) P1
        PIVOT( MAX(Blank) FOR CourseNameBlank IN ([Math_Blank], [English_Blank])) P2
        PIVOT( MAX(Wrong) FOR CourseNameWrong IN ([Math_Wrong], [English_Wrong])) P3
        PIVOT( MAX(Score) FOR CourseNameScore IN ([Math_Score], [English_Score])) P4
        GROUP BY StudentName
    
    StudentName Math_Correct Math_Blank  Math_Wrong  Math_Score  English_Correct English_Blank English_Wrong English_Score
    ----------- ------------ ----------- ----------- ----------- --------------- ------------- ------------- -------------
    Student1    38           2           0           95          45              5             0             90
    Student2    38           2           0           95          45              5             0             90
    
    0 讨论(0)
提交回复
热议问题