Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to learn more on 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   

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?

like image 354
10e5x Avatar asked Jan 16 '13 09:01

10e5x


People also ask

What is the use of Ntile function?

Distributes the rows in an ordered partition into a specified number of groups. The groups are numbered, starting at one. For each row, NTILE returns the number of the group to which the row belongs.

What will happen if there are 53 rows and you try Ntile 5?

For example if the total number of rows is 53 and the number of groups is five, the first three groups will have 11 rows and the two remaining groups will have 10 rows each. If on the other hand the total number of rows is divisible by the number of groups, the rows will be evenly distributed among the groups.

How is Ntile calculated?

NTILE simply divides up a set of data evenly by the number provided (as noted by RoyiNamir above). If you chart the results of both functions, NTILE will be a perfectly linear line from 1-to-n, whereas percentile rank will [usually] have some curves to it depending on your data.

What does Ntile mean?

NTILE is an analytic function. It divides an ordered data set into a number of buckets indicated by expr and assigns the appropriate bucket number to each row. The buckets are numbered 1 through expr . The expr value must resolve to a positive constant for each partition.


1 Answers

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

like image 152
SQLMenace Avatar answered Oct 05 '22 06:10

SQLMenace