mysql - SQL: Calculate time spent one each page -
i have 2 tables:
pages: id | page | date | visit_id ---- ---------- --------- ------------ 1 1 2015-05-07 13:53:50 1 2 2 2015-05-07 13:53:54 1 3 3 2015-05-07 13:54:10 1 4 4 2015-05-07 13:54:49 1 5 1 2015-05-07 14:54:15 2 6 3 2015-05-07 14:54:30 2 7 4 2015-05-07 14:54:37 2 visits: id | end_date ---- --------- 1 2015-05-07 13:54:55 2 2015-05-07 14:54:50
i want average time spend on each page, after running query, final result should this:
page count(seconds) 1 9.5 2 16 3 23 4 9.5
the last page user visited it's calculated using end_date in visits table.
any ideas how query like?
edit: calculation example:
page 1 avg seeconds = (2015-05-07 13:53:54 - 2015-05-07 13:53:50 + 2015-05-07 14:54:30 - 2015-05-07 14:54:15) /2 last page avg = (2015-05-07 13:54:55 - 2015-05-07 13:54:49 + 2015-05-07 14:54:50 - 2015-05-07 14:54:37) / 2
considering following data set:
drop table if exists pages; create table pages (id int not null auto_increment primary key ,page int not null ,date datetime not null ,visit_id int not null ); insert pages values (1,1,'2015-05-07 13:53:50',1), (2,2,'2015-05-07 13:53:54',1), (3,3,'2015-05-07 13:54:10',1), (4,4,'2015-05-07 13:54:49',1), (5,1,'2015-05-07 14:54:15',2), (6,3,'2015-05-07 14:54:30',2), (7,4,'2015-05-07 14:54:37',2); drop table if exists visits; create table visits (id int not null ,end_date datetime not null ); insert visits values (1,'2015-05-07 13:54:55'), (2,'2015-05-07 14:54:50');
an intermediate result might this:
select p.* , time_to_sec(timediff(coalesce(min(x.date),v.end_date),p.date)) n pages p left join pages x on x.visit_id = p.visit_id , x.date > p.date join visits v on v.id = p.visit_id group p.id; +----+------+---------------------+----------+------+ | id | page | date | visit_id | n | +----+------+---------------------+----------+------+ | 1 | 1 | 2015-05-07 13:53:50 | 1 | 4 | | 2 | 2 | 2015-05-07 13:53:54 | 1 | 16 | | 3 | 3 | 2015-05-07 13:54:10 | 1 | 39 | | 4 | 4 | 2015-05-07 13:54:49 | 1 | 6 | | 5 | 1 | 2015-05-07 14:54:15 | 2 | 15 | | 6 | 3 | 2015-05-07 14:54:30 | 2 | 7 | | 7 | 4 | 2015-05-07 14:54:37 | 2 | 13 | +----+------+---------------------+----------+------+
...and complete query might therefore this...
select page,avg(n) ( select p.* , time_to_sec(timediff(coalesce(min(x.date),v.end_date),p.date)) n pages p left join pages x on x.visit_id = p.visit_id , x.date > p.date join visits v on v.id = p.visit_id group p.id ) group page; +------+---------+ | page | avg(n) | +------+---------+ | 1 | 9.5000 | | 2 | 16.0000 | | 3 | 23.0000 | | 4 | 9.5000 | +------+---------+
Comments
Post a Comment