views:

28

answers:

2

I have a table setup like this (simplified for example):

user_id
item_id
click_dt

Each item_id has many user_id's. Basically it's storing the clicks on items, associated to a user_id.

I want to query through this and list only the latest user_id for each item_id, based on click_dt.

So if there are 5 clicks for item_id 55, the last click or click_dt DESC would be the record to show....

Make sense? Any help would be awesome... thanks!

+1  A: 

Use:

SELECT x.*
  FROM YOUR_TABLE x
  JOIN (SELECT t.item_id,
               MAX(t.click_dt) AS max_date
          FROM YOUR_TABLE t
      GROUP BY t.item_id) y ON y.item_id = x.item_id
                           AND y.max_date = x.clicked_dt

Alternate:

SELECT x.item_id,
       x.user_id,
       x.click_dt
  FROM (SELECT t.item_id,
               t.user_id,
               t.click_dt,
               CASE
                 WHEN @item = t.item_id THEN @rownum := @rownum + 1
                 ELSE @rownum := 1
              END AS rk,
              @item := t.item_id
         FROM YOUR_TABLE t
         JOIN (SELECT @rownum := 0, @item := 0) r
     ORDER BY t.itemid, click_dt DESC) x
 WHERE x.rk = 1
OMG Ponies
@OMG Ponies: How do you format your queries? Or are they handwritten so sexy?
zerkms
wow! Thanks so much, never would have came up with those... both work, but the Alternate seems to be about twice as fast. I've had to add in a join also for a users table within the sub select... it's 8x faster than what I had previously (which wasn't even returning the right results!)
dave
A: 

Try this:

SELECT user_id,item_id,click_dt FROM
(
    SELECT MAX(click_dt) AS LastClick_dt,item_id FROM aTable
    GROUP BY item_id
) As LastClick
INNER JOIN aTable 
ON aTable.itemid = LastClick.item_id
AND aTable.click_dt = LastClick.LastClick_dt

The subselect part will give the latest click for each item_id, and then you can join this to the original table to retrieve the matching user_id.

Kibbee