SQL Tutorial
|
|
|
|
| Articles Reviews Structured Query Language | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| Written by Bogdan V | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| Thursday, 14 September 2006 | ||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Page 16 of 17 {mos_sb_discuss:29}
SQL Rank
Displaying the rank associated with each row is a common request, and
there is no straightforward way to do so in SQL. To display rank in
SQL, the idea is to do a self-join, list out the results in order, and
do a count on the number of records that's listed ahead of (and
including) the record of interest. Let's use an example to illustrate.
Say we have the following table, Table Total_Sales
we would type,
SELECT a1.Name, a1.Sales, COUNT(a2.sales) Sales_Rank Result:
Let's focus on the WHERE clause. The first part of the clause,
(a1.Sales <= a2.Sales), makes sure we are only counting the number
of occurrences where the value in the Sales column is less than or
equal to itself. If there are no duplicate values in the Sales column,
this portion of the WHERE clause by itself would be sufficient to
generate the correct ranking. The second part of the clause, (a1.Sales=a2.Sales and a1.Name = a2.Name), ensures that when there are duplicate values in the Sales column, each one would get the correct rank. SQL Median To get the median, we need to be able to accomplish the following:
· Sort the rows in order and find the rank for each row.
Let's use an example to illustrate. Say we have the following table, Table Total_Sales
we would type,
SELECT Sales Median FROM Result:
You will find that Lines 2-6 are the same as how we find the rank of
each row. Line 7 finds the "middle" rank. DIV is the way to find the
quotient in MySQL, the exact way to obtian the quotient may be
different with other databases. Finally, Line 1 obtains the value for
the middle-ranked row. |
||||||||||||||||||||||||||||||||||||||||||||||||||||
| Last Updated ( Saturday, 30 June 2007 ) | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| < Prev |
|---|







