Search code examples
sqlsql-serversql-server-2005ansi-sql

SQL statement to select the value of the latest version of data based on the latest date


I have a simple query and am wondering if it could be more elegantly coded. The final solution has to be ansi-compliant.

I need to fetch the latest value from a table based on date and version. A sample would explain more clearly:

declare @t table (id int, due_date smalldatetime, version int, value nvarchar(10))

insert into @t select 3, '1/1/2010', 1, 'value 1'
insert into @t select 3, '1/1/2010', 2, 'value 2'
insert into @t select 3, '3/1/2010', 1, 'value 3'
insert into @t select 3, '3/1/2010', 2, 'value 4'
insert into @t select 3, '3/1/2010', 3, 'value 5'
insert into @t select 3, '3/1/2010', 4, 'value 6'
insert into @t select 3, '4/1/2010', 1, 'value 7'
insert into @t select 3, '4/1/2010', 2, 'value 8'
insert into @t select 3, '4/1/2010', 3, 'value 9'


select value from @t t
    inner join (select due_date, version=max(version) 
                from @t where due_date = (select max(due_date) from @t) group by due_date) maxes
    on t.due_date=maxes.due_date and t.version=maxes.version

So I would expect the output to be

value 9

which it is based on the above query.

I'm not particulary happy with this solution - any better ways to accomplish this?


Solution

  • You could use:

      SELECT TOP 1 
             x.value
        FROM @t x
    ORDER BY x.due_date DESC, x.version DESC
    

    TOP is not ANSI, though. Another option would be to use ANSI analytical/rank/windowing functions:

    SELECT x.value
      FROM (SELECT t.value,
                   ROW_NUMBER() OVER (ORDER BY t.due_date DESC, t.version DESC) AS rank
              FROM @t t) x
     WHERE x.rank = 1
    

    But this requires a database that supports the functionality - MySQL doesn't, PostgreSQL only started in v8.4...