I'm trying to generate a little report based on some data.
The data structure is like this:
Basically it's a list of user_ids from a user accounts table, and the page_number is the number of the page that that particular user navigated to in the search results on our site. So if I searched for some topic, and got 8 pages of results back, and clicked on the page 7 link, that would be recorded as (my user id) | 7.
What I need to do is pull the top 10 user ids out of this based on the highest page number they reached. This presents a problem because I need distinct user ids based on the max page_number, but can't form a SQL query to give me this! It's frustrating me so I seek the help of others.
Here's what I've got so far, tell me if I'm on the right track:
The idea here is "get the top 10 user ids from this table where the user id equals this other user id selected based on it being the max page_number for this user id in the table".
Obviously this doesn't work as I have some contraint issues with the page_number variable not being in a function.
Any ideas? Do I need to use a cursor here and some actual manual comparison/logic to handle this, or can it be done with SQL lingo?? Thanks!
The data structure is like this:
Code:
user_id page_number
------------------------
1 22
1 21
1 20
3 18
3 17
6 23
6 22
...
...
Basically it's a list of user_ids from a user accounts table, and the page_number is the number of the page that that particular user navigated to in the search results on our site. So if I searched for some topic, and got 8 pages of results back, and clicked on the page 7 link, that would be recorded as (my user id) | 7.
What I need to do is pull the top 10 user ids out of this based on the highest page number they reached. This presents a problem because I need distinct user ids based on the max page_number, but can't form a SQL query to give me this! It's frustrating me so I seek the help of others.
Here's what I've got so far, tell me if I'm on the right track:
Code:
SELECT TOP 10 a.user_id
FROM activity_table a
GROUP BY a.user_id
HAVING a.page_number = (
SELECT MAX(page_number)
FROM activity_table
WHERE user_id = a.user_id
)
The idea here is "get the top 10 user ids from this table where the user id equals this other user id selected based on it being the max page_number for this user id in the table".
Obviously this doesn't work as I have some contraint issues with the page_number variable not being in a function.
Any ideas? Do I need to use a cursor here and some actual manual comparison/logic to handle this, or can it be done with SQL lingo?? Thanks!