[英]How can I group student scores into quintile using SQL Server 2008
Can anyone help me to group student scores into quintile? 谁能帮助我将学生成绩分为五等分? I think there is a feature in SQL Server 2012, but still we haven t upgraded to it as we are using 2008R2. I tried
我认为SQL Server 2012中有一项功能,但是t upgraded to it as we are using 2008R2. I tried
仍未t upgraded to it as we are using 2008R2. I tried
t upgraded to it as we are using 2008R2. I tried
Ntile(5)` but it is not generating the desired result. t upgraded to it as we are using 2008R2. I tried
Ntile(5)`,但未产生期望的结果。 I need below Quintile column 我需要在昆泰栏下面
Student Score Quintile
------------------------
Student1 20 1
Student2 20 1
Student3 30 2
Student4 30 2
Student5 40 2
Student6 40 2
Student7 50 3
Student8 50 3
Student9 60 3
Student10 70 4
Student11 70 4
Student12 80 4
Student13 80 4
Student14 90 5
You must have been doing something wrong when using NTILE(5)
- that IS the function to use! 使用NTILE(5)
时,您一定做错了-这就是要使用的功能!
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 从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``
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.