Saturday, November 12, 2011

0 Ranking Function: Row Number,Rank,DESN Rank and NTILE

 

Ranking function syntax are similar for all 4 different type of ranking functions.

  1. [ROW_NUMBER()|RANK() |DENSE_RANK ( )|NTILE()]    OVER ( [ <partition_by_clause> ] < order_by_clause > )

Partition: use for group the result set.

  • Row Number: Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.
  • Rank: Returns the rank of each row within the partition of a result set. The rank of a row is one plus the number of ranks that come before the row in question.
  • DENSE_RANK: Similer to Rank but without the gap.
  • NTILE: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.

ROW_NUMBER

  1. SELECT PSC.Name Category,p.Name Product,p.ListPrice,
  2. ROW_NUMBER() OVER(PARTITION BY PSC.Name ORDER BY P.ListPrice DESC) AS Row
  3. FROM Production.Product p
  4. JOIN Production.ProductSubCategory PSC
  5. ON p.ProductSubCategoryID=PSC.ProductSubCategoryID
  6. ORDER BY Category,ListPrice DESC

Because we partition by PSC.Name( Category) therefore you can see the result has been group as many subset group.

image

RANK

  1. SELECT Name ,ListPrice,
  2. RANK() OVER(ORDER BY ListPrice DESC) AS Rank
  3. FROM Production.Product

image

DENSE_RANK

  1. SELECT Name ,ListPrice,
  2. DENSE_RANK() OVER(ORDER BY ListPrice DESC) AS Rank
  3. FROM Production.Product

image

NTITLE

Below example divide the result set to 10 groups and then shows which group the row belong to.

  1. SELECT NTILE(10) OVER(PARTITION BY PC.Name ORDER BY P.ListPrice DESC) AS PriceBand,
  2. pc.Name Category,p.Name Produc,p.ListPrice
  3. FROM Production.Product p
  4. JOIN Production.ProductSubCategory PSC
  5. ON p.ProductSubCategoryID=PSC.ProductSubCategoryID
  6. JOIN Production.ProductCategory pc
  7. ON PSC.ProductCategoryID=pc.ProductCategoryID
  8. ORDER BY Category,ListPrice DESC

image

0 comments:

Post a Comment

 

SQL Panda Copyright © 2011 - |- Template created by O Pregador - |- Powered by Blogger Templates