If repetitive values exist, the same rank would be assigned to all of them.
For each duplicate value, the RANK() function skips the subsequent value so that the next non-duplicate value remains in its rightful position.
Examples:
You can rank Integer type of column values.
SELECT RANK() OVER(ORDER BY budget DESC)
FROM department
WHERE budget <= 50000
You can rank any kind of data values. The following is varchar.
Select RANK() over(Order by region desc) as Rank, region
from employee
Rank Region
------------ --------------
1 West
1 West
3 South
3 South
5 North
5 North
5 North
8 East
8 East
DENSE_RANK():
Finds rank of for given column with subsequent increment even for duplicates.
The main difference between RANK() and DENSE_RANK() is that for duplicates(repetitive) values, RANK() skips sub-sequent rank value
whereas DENSE_RANK() does not skips and continues with next sub-sequent rank.
It computes the variance of all the values listed in a column. i.e,
It returns measure of how far the extreme low range or high range value is from the middle.
Examples:
SELECT VAR(salary) AS Expr1
FROM employee
VARP():
It is similar to VAR() but finds variance of entire data not only extreme low or high.
Examples:
SELECT VARP(salary) AS Expr1 – - P Stands for Population.
FROM employee
ROW_NUMBER() OVER():
Returns the sequential number for each row within a result set, starting from 1.
Syntax:
ROW_NUMBER ( ) OVER ([<partition_by_clause>] <order_by_clause>)
Examples:
SELECT row_number() over(ORDER BY name)
FROM student
where name='aaa'=> 1
Find the second maximum using ROW_NUMBER() function.
// Following doesn’t work if column have repetitive values.
Select Salary
From ( SELECT salary,
ROW_NUMBER() OVER(ORDER BY salary DESC) as c
FROM employee) as t
where t.c=2
// The following works with repetitive valued columns.
Select m1
From ( SELECT m1, ROW_NUMBER() OVER (ORDER BY s1.m1 DESC) as r
from (SELECT DISTINCT m1 from student) as s1 ) as t
Where t.r =2
Interpretation:
Inline-View
S1: Select DISTINCT m1 from Student
Inline-View
t : Select m1, Row_Number() OVER (ORDER BY
s1.m1 DESC) from S1
No comments:
Post a Comment