views:

35

answers:

1

Let's say I have a table T_SWA .This is my prepared statement. Select version from (Select id, version,creator,created_date ROW_NUMBER() OVER(order by created_date) cnt From T_SWA where cnt=3 and id=35); I need to select the 3rd recent version from the T_SWA table..Can anyone suggest a replacement for this query without using ROW_NUM() and OVER() functiions?

A: 

First take the three most recent and then from those three take the first.

select id, version, creator, created_date 
from (
    select id, version, creator, created_date 
        from T_SWA
        where id = 35
        order by created_date desc
        fetch first 3 rows only
)
order by created_date
fetch first 1 row only;
Frans
When i tried to find the nth record , a datatype mismatch occurs, possibly at the place where the fetch keyword is being used.Can the Fetch keyword be used to find the nth record??
No. See http://stackoverflow.com/questions/3751884/paramertize-fetch-first-n-rows-only-in-db2/3774458#3774458 and then the second comment.
Frans
WARNING: This solution will only work if there are 3 records for a particular ID. If you have 30 records, this solution would return the 28th oldest record (when ordered by created_date), not the third oldest record. The subselect needs to be done in ascending order, and the outer select should be done in descending order.
Ian Bjorhovde
WARNING?: I do not agree. Maybe there is some misunderstanding about what the requested '3rd recent version' does mean. Let's assume there is a version for every day of september 2010. There will be 30 records from 1 till 30 september in the table. The '3rd recent version' would be the version of 28 september. The inner select, ordered by created_date desc, will return september 30, 29 and 28. The outer select, ordered by created_date, will return september 28. Am I missing something?
Frans