views:

72

answers:

2

Hello,

I am tracking page views within modules using the following table:

id | page_id | user_id | session_id | created

Every page is unique to a certain module; so page 14 only exists in module 2, for instance.

I am trying to write a query that tells me when a viewing session began (GROUP BY session_id) for a particular module, but I am having trouble with my ordering. Basically, for that grouped session, I want to return the earliest 'created' (the starting time of the viewing session) and the latest page_id (how far they got within the module).

What is the best way to accomplish this?

+1  A: 
SELECT  MIN(created), MAX(page_id)
FROM    modules
GROUP BY
        session_id
Quassnoi
I don't believe that will show the desired results - the MAX(page_id) I think needs to correspond to the last created time.
BrynJ
@BrynJ: Based on the OP's definition of "how far they got within the module" @Quassnoi would still be right.
Tomalak
+2  A: 

I think you'll need to utilise sub-queries in the select:

SELECT a.session_id, MIN(a.created) as start_time, 
b.page_id AS last_page, b.end_time
FROM table a 
INNER JOIN 
   (SELECT b.session_id, MAX(b.created) as end_time, MAX(b.page_id) 
   FROM table b GROUP BY b.session_id) 
ON a.session_id = b.session_id GROUP BY a.session_id
BrynJ