Search code examples
sql-serverselectdate-sorting

How to select unique row according to last accessed time


I want to get only distinct rows with their respective AnsId,

like Qid: 01 have last AnsId: 01

I have following data structure,

Qid  Time                  AnsId
01   2011-09-26 12:55:10   01
02   2011-09-26 12:58:32   03
03   2011-09-26 12:59:05   02
01   2011-09-26 01:02:10   01
03   2011-09-26 01:30:10   01
02   2011-09-26 01:59:10   02

I have written following query but it returns all the rows:

SELECT DISTINCT Qid, Time, AnsId
FROM table
ORDER BY Time DESC

Then what is missing part in the select query?


Solution

  • You could use row_number() to find the last answer per Qid:

    select  *
    from    (
            select  row_number() over (partition by Qid order by Time desc) as rn
            ,       *
            from    YourTable
            ) as SubQueryAlias
    where   rn = 1
    

    The subquery is required because SQL Server doesn't allow row_number directly in a where.