Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h1>SQL Server 2000 and above</h1> <p>Based on your requirement, you need to find the most recent effective date within each rank. To achieve, you need to write a sub query that would fetch the maximum effective date for a given rank and then compare it with the date in the row to filter down to the required results. This will work in all versions from SQL Server 2000 and above.</p> <p>Following query has been tested in SQL Server 2000.</p> <p><a href="http://sqlfiddle.com/#!6/917db/16" rel="nofollow"><strong>Click here to view the demo in SQL Fiddle</strong></a></p> <p><em>Script</em>:</p> <pre><code>SELECT TOP 10 id , rank_id , week_id , rider_id , year_no , rank_no , effective_dt , lastupdate_dt , point_no , average_no , result_qy FROM ranking r_outer WHERE rank_id = 1950 AND effective_dt = ( SELECT MAX(effective_dt) FROM ranking r_inner WHERE r_inner.rank_no = r_outer.rank_no AND r_inner.rank_id = 1950 ) ORDER BY rank_no; </code></pre> <h1>SQL Server 2005 and above</h1> <p>You need to use <strong><code>RANK</code></strong> function that would partition the results by <code>rank_no</code> column and sort each partition by <code>rank_no</code> followed by <code>effective_dt</code> in descending order. Each sorted partition section will be assigned a rank value like 1, 2, 3 etc. You are interested in only the first rank of each of these partition groups. So, hence the outer SELECT to filter the results by <code>rank_num = 1</code>.</p> <p><em>RANK</em> function is supported only in <em>SQL Server 2005 and above</em>.</p> <p><a href="http://sqlfiddle.com/#!6/917db/3" rel="nofollow"><strong>Click here to view demo in SQL Fiddle using SQL Server 2012.</strong></a></p> <p>Script:</p> <pre><code>SELECT TOP 10 id , rank_id , week_id , rider_id , year_no , rank_no , effective_dt , lastupdate_dt , point_no , average_no , result_qy FROM ( SELECT id , rank_id , week_id , rider_id , year_no , rank_no , effective_dt , lastupdate_dt , point_no , average_no , result_qy , RANK() OVER( PARTITION BY rank_no ORDER BY rank_no, effective_dt DESC) rownum FROM ranking r WHERE r.rank_id = 1950 ) t1 WHERE rownum = 1; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload