Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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  

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
361 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

example

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

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

If you add one more row

insert #temp  values('S6',92 ) 

Now both buckets have 3 rows

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...