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

雨燕双飞 提交于 2019-12-02 14:11:32

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:

Borrowed from marc_s +1

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 s.StudentName, s.Score, qm.maxQ   FROM @Students as s   join ( select score, MAX(Quintile) as maxQ            from ( SELECT Score, Quintile = NTILE(5) OVER(ORDER BY Score)                     FROM  @Students ) q            group by q.score ) qm     on qm.Score = s.Score 
Below is the correct answer given by Erland Sommarskog  Create Table #Scores(Student varchar(20), Score int);  Insert #Scores(Student, Score) Values  ('Student1', 20)  ,('Student2', 20)  ,('Student3', 30) ,('Student4', 30) ,('Student4', 30) ,('Student4', 30) ,('Student5', 40) ,('Student6', 40) ,('Student7', 50) ,('Student8', 50) ,('Student9', 60) ,('Student10', 70) ,('Student11', 70)  ,('Student12', 80)  ,('Student13', 80)  ,('Student14', 90);   ; WITH quintiles AS (     SELECT Score, ntile(5) OVER(ORDER BY Score) AS quintile      FROM   (SELECT DISTINCT Score FROM #Scores) AS s  ) SELECT s.Student, s.Score, q.quintile FROM   #Scores s JOIN   quintiles q ON s.Score = q.Score go DROP TABLE #Scores  --by Erland Sommarskog`` 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!