How can I group student scores into quintile using SQL Server 2008

前端 未结 3 1756
忘掉有多难
忘掉有多难 2021-01-29 08:40

Can anyone help me to group student scores into quintile? I think there is a feature in SQL Server 2012, but still we havent upgraded to it as we are using 2008R2. I tried

3条回答
  •  灰色年华
    2021-01-29 09:33

    You must have been doing something wrong when using NTILE(5) - that IS the function to use!

    Here's my test setup:

    DECLARE @Students TABLE (StudentID INT IDENTITY(1,1), StudentName VARCHAR(20), Score INT)
    
    INSERT INTO @Students(StudentName, Score)
    VALUES ('Student 1', 20), ('Student 2', 20), 
    ('Student 3', 30), ('Student 4', 30), 
    ('Student 5', 40), ('Student 6', 40), 
    ('Student 7', 50), ('Student 8', 50), 
    ('Student 9', 60), 
    ('Student 10', 70), ('Student 11', 70), 
    ('Student 12', 80), ('Student 13', 80), 
    ('Student 14', 90)
    
    
    SELECT 
        StudentName, Score, 
        Quintile = NTILE(5) OVER(ORDER BY Score)
    FROM    
        @Students
    

    And the output is:

    enter image description here

提交回复
热议问题