While trying to write a report that lists the top paths that visitors took through an application I ran into something I couldn't figure out how to address in SQL. I ended up scripting a solution, but whenever I can't figure out how to do something in SQL I wonder if I'm missing something.
So first up, the problem.
There is a PageViews table like so
page_name is the name of the visited page.
From this data, I wanted to extract the most popular "flows" which are defined as a sequence of page_names that start with "Home", have a consistent visitor_id and proceed in chronological order by visit_timestamp and do not contain any further "Home" entries.
So, with sample data:
The report would spit out:
My solution was to write a script that did a loop on
and assigned a unique session id every time it encountered a "Home" page_view, and copied the result into a new table.
I then used group_contact (db specific function to mysql and sqlite, postgres has string_agg, there are others) to group on session_id and smush the page_names into a string.
It seems to work OK, though it's certainly not efficient.
So, am I missing something obvious? Would I be able to extract the report I want from that table structure using only sql?
My thought is that moving forward we should store the tracking data in a table structure that's easier to query.
So first up, the problem.
There is a PageViews table like so
Code:
vistor_id | page_name | visit_timestamp
page_name is the name of the visited page.
From this data, I wanted to extract the most popular "flows" which are defined as a sequence of page_names that start with "Home", have a consistent visitor_id and proceed in chronological order by visit_timestamp and do not contain any further "Home" entries.
So, with sample data:
Code:
1 | Home | 1
2 | Home | 2
1 | PageA | 3
2 | PageB | 4
3 | Home | 5
3 | PageA | 6
1 | Home | 7
1 | PageA | 8
The report would spit out:
Code:
Count | Flow
-------------------
3 | Home, PageA
1 | Home, PageB
My solution was to write a script that did a loop on
Code:
select visitor_id, page_name from PageViews order by vistory_id, visit_timestamp
and assigned a unique session id every time it encountered a "Home" page_view, and copied the result into a new table.
I then used group_contact (db specific function to mysql and sqlite, postgres has string_agg, there are others) to group on session_id and smush the page_names into a string.
Code:
select count(*) as count, flow from (select group_concat(page_name) as flow from PageViewsWithSessionId
group by visitor_id order by visit_timestamp) group by flow order by count desc limit 100;
It seems to work OK, though it's certainly not efficient.
So, am I missing something obvious? Would I be able to extract the report I want from that table structure using only sql?
My thought is that moving forward we should store the tracking data in a table structure that's easier to query.