Today I needed to find the average session length for our site visitors. We keep a stats log for our site visitors that login. So I know when they logged in, and I know when they clicked the logout button. Not all customers click the logout button (about 55% do), but for our purposes it was good enough to only count those customers who click logout. It is hard to know exactly when their session ended if they don’t click logout.
The trouble I ran into was that I was dealing with data like this:
The first column is session IDs (I have truncated them from the real session IDs). The second column has 2 dates, representing the login time and the logout time for each session. So how can I take data like that and find the session length for each individual session? Here is one method (there may be better ways to do this):
select jsessionID, sessionLength=dateDiff(second,min(visitDate),max(visitDate))from tempStatsgroup by jsessionIDorder by sessionLength desc
The trick here is that you are using both the SQL Min and Max functions to aggregate the two dates into one row. Then you just have to use the dateDiff function to find the session length. In this case I am getting the session length in seconds. For the above sample records, this is the result:
This code was written for SQL Server 2005…I’m not sure if it will work in other databases, but if not I’m sure something similar will.