想了解更多关于 NTILE() [英] Want to learn more on NTILE()

查看:33
本文介绍了想了解更多关于 NTILE()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 ms sql 的 RANKING 函数.我理解除 NTILE() 之外的其他函数.假设我有这些数据:

I was reading on RANKING function for ms sql. I understand the others function except NTILE(). Lets say if i have this data:

   StudentID     MARKS  
      S1           75  
      S2           83
      S3           91
      S4           83
      S5           93  

因此,如果我执行 NTILE(2) OVER(ORDER BY MARKS desc) 结果会是什么,为什么?
如果它是 NTILE(3) 呢?简单的解释有人吗?

So if i do a NTILE(2) OVER(ORDER BY MARKS desc) what will be the result and why?
And what if it is a NTILE(3)? Simple explaination anyone?

推荐答案

把它想象成一个桶,NTILE(2) 会生成 2 个桶,一半的行的值为 1,另一半的值为 2

Think of it as buckets, NTILE(2) will make 2 buckets, half the rows will have the value 1 and the other half the value 2

示例

create table  #temp(StudentID char(2),    Marks  int) 
insert #temp  values('S1',75 ) 
insert #temp  values('S2',83)
insert #temp  values('S3',91)
insert #temp  values('S4',83)
insert #temp  values('S5',93 ) 


select NTILE(2) over(order by Marks),*
from #temp
order by Marks

这里是输出,因为你的行数是奇数,桶 1 将多 1 行

Here is the output, since you have an uneven number of rows, bucket 1 will have 1 row more

1   S1  75
1   S2  83
1   S4  83
2   S3  91
2   S5  93

如果再添加一行

insert #temp  values('S6',92 ) 

现在两个桶都有 3 行

Now both buckets have 3 rows

1   S1  75
1   S2  83
1   S4  83
2   S3  91
2   S6  92
2   S5  93

实际上,我从未在生产代码中使用过 NTILE,但我可以看到需要将结果拆分为 n 个桶的用途

In reality I have never used NTILE in production code but I can see the use where you need to split the results into n number of buckets

这篇关于想了解更多关于 NTILE()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆