How to find distinct top X values?

  • I'm sure this is simple but I'm just not getting it.....can someone help me?

    I have a log table that logs a row every time an item is hit, and the datetime that it was accessed. I want to create a Most Recently Viewed list based on this data.

    Essentially I want the 5 most recent *different* items that were accessed. My table has username, itemid, and dateaccessed. I want something like this:

    select distinct top 5

    itemid

    from tblhits

    where username='testusername'

    order by dateaccessed desc

    This of course doesn't work because dateaccessed isn't part of the distinct query. How can I do this? Thanks!!

  • You can use a subquery or a CTE. Either one will do the same thing, but the CTE is more readable if you are using SQL Server 2005.

    For instance:

    ; with CTE1 as (

    select distinct top 5

    itemid, dateaccessed

    from tblhits

    where username='testusername'

    order by dateaccessed desc

    )

    select itemid

    from CTE1

    ---
    Timothy A Wiseman
    SQL Blog: http://timothyawiseman.wordpress.com/

  • Doh, I'm on SQL2000 for a month or so longer until we finish the upgrade to 2005....what's the CTE again?

    The subquery seems to work, it just takes longer than what I'd prefer. Maybe that's the best I can do, I'll have to run the analyzer and see if I can optimize it some. Is there no better way of doing this?

    Thanks again for your help!

  • CTE (Common Table Expressions) were introduced in 2005 and can make certain things easier.

    I cannot think of any way to speed it up immediately.

    ---
    Timothy A Wiseman
    SQL Blog: http://timothyawiseman.wordpress.com/

  • Or something like this?

    SELECTTOP 5 T.*

    FROM( SELECT itemid, MAX( dateaccessed ) AS SNO FROM tblhits WHERE username = 'testusername' GROUP BY itemid ) T

    ORDER BY SNO DESC

    --Ramesh


  • Ramesh (12/6/2007)


    Or something like this?

    SELECTTOP 5 T.*

    FROM( SELECT itemid, MAX( dateaccessed ) AS SNO FROM tblhits WHERE username = 'testusername' GROUP BY itemid ) T

    ORDER BY SNO DESC

    Thank you, this seems to work great!

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply