-1 sql t-sql sql-server sql-server-2008-r2 ranking-functions
谁能帮我把学生的分数分成五分之一?我认为 SQL Server 2012 中有一个功能,但我们仍然没有t upgraded to it as we are using 2008R2. I tried
Ntile(5)`,但它没有生成所需的结果。我需要低于五分位数列
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
Run Code Online (Sandbox Code Playgroud)
您在使用时一定是做错了什么NTILE(5)
- 这就是要使用的功能!
这是我的测试设置:
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
Run Code Online (Sandbox Code Playgroud)
输出是: