views:

30

answers:

2

I have a table tblSequence with 3 cols in MS SQL: ID, IP, [Timestamp]

Content could look like this:

ID          IP              [Timestamp]
--------------------------------------------------
4347        62.107.95.103   2010-05-24 09:27:50.470
4346        62.107.95.103   2010-05-24 09:27:45.547
4345        62.107.95.103   2010-05-24 09:27:36.940
4344        62.107.95.103   2010-05-24 09:27:29.347
4343        62.107.95.103   2010-05-24 09:27:12.080

ID is unique, there can be n number of IP's.

Would like to calculate the average time spent per IP. in a single row

Know you can do something like this:

SELECT CAST(AVG(CAST(MyTable.MyDateTimeFinish - 
         MyTable.MyDateTimeStart AS float)) AS datetime)

But how on earth do I find the first and last entry of my unique IP row so I can have a start and finish time? I'M stuck.

Would like to calculate the average time spent per IP. in a single row

+1  A: 

But how on earth do I find the first and last entry of my unique IP row so I can have a start and finish time? I'M stuck.

Select IP, MIN([Timestamp]) as MinTime,  Max([Timestamp]) as MaxTime
from your table
group by IP
SQLMenace
The bad news is this will see 2 visits 3 days apart and report 72 hours. Is this desired behavior? I am assuming he is after some kind of session length, and would want all times in a row with no more than ~30 minutes between them.
bwawok
1.How do I write the entire SQL then with the function above?2.Would like to include a WHERE clause - how to do that combined with Group BY?
seo20
I have another column with a unique session ID. IP serves only as an example to do it with a nvarchar.
seo20
+1  A: 
Charles Bretana
There can be multiple rows with none-unique SessionGuids. Right now this does not filter out duplicates or uses group by. What to do?
seo20
This is my current SQL:SELECT s.[SessionGuid], s.[siteID], e.[TimeStamp] - s.[TimeStamp] as TimeSpent FROM tblSequence s Join tblSequence E On e.[SessionGuid] = s.[SessionGuid] And e.TimeStamp = (SELECT Max([TimeStamp]) FROM tblSequence WHERE [SessionGuid] = s.[SessionGuid]) WHERE s.TimeStamp = (SELECT Min([TimeStamp]) FROM tblSequence WHERE [SessionGuid] = s.[SessionGuid])AND s.[siteID] = 15 ORDER BY s.[sessionGuid], TimeSpent
seo20
because of the where clause which restreicts the main query from producing rows with timestamps that are not the earliest timestamp for each sessionGuid, This should give you only one row per sessionGuid. Are there multiple rows with the same sessionGuid and the same timestamp ???
Charles Bretana
There is a problem if there is only ONE row with unique SessionGuid. Then it seems the max and min routine return zero time spent.
seo20
Then That means there is onlyu a "start" time and not another row to get the "end" Time from... What do you want to do then?? Count the elapsed time from start to now ?
Charles Bretana