使用 NTILE 将数据划分为等分区的桶

假设你有多个考试的考试成绩,并且你希望将每个考试分成四分位数。

-- Setup data:
declare @values table(Id int identity(1,1) primary key, [Value] float, ExamId int)
insert into @values ([Value], ExamId) values
(65, 1), (40, 1), (99, 1), (100, 1), (90, 1), -- Exam 1 Scores
(91, 2), (88, 2), (83, 2), (91, 2), (78, 2), (67, 2), (77, 2) -- Exam 2 Scores

-- Separate into four buckets per exam:
select ExamId, 
       ntile(4) over (partition by ExamId order by [Value] desc) as Quartile, 
       Value, Id 
from @values 
order by ExamId, Quartile

StackOverflow 文档

当真正需要一定数量的桶并且每个桶都填充到大致相同的水平时,ntile 效果很好。请注意,通过简单地使用 ntile(100) 将这些分数分成百分位数是微不足道的。