SQL Puzzle

Status
Not open for further replies.

Josh

Ars Praefectus
3,533
Subscriptor
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

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.
 

C0rinthian

Ars Tribunus Angusticlavius
6,858
EDIT: This is on Oracle.

Hierarchical queries will do what you want, but they're a bit harder use with the data provided since you don't have explicit parent/child fields to reference.

Code:
CREATE TABLE tmp (
    visitor_id NUMBER,
    page_name VARCHAR2(16),
    visit_timestamp NUMBER
);

INSERT INTO tmp (visitor_id, page_name, visit_timestamp) VALUES (1, 'Home', 1);
INSERT INTO tmp (visitor_id, page_name, visit_timestamp) VALUES (2, 'Home', 2);
INSERT INTO tmp (visitor_id, page_name, visit_timestamp) VALUES (1, 'PageA', 3);
INSERT INTO tmp (visitor_id, page_name, visit_timestamp) VALUES (2, 'PageB', 4);
INSERT INTO tmp (visitor_id, page_name, visit_timestamp) VALUES (3, 'Home', 5);
INSERT INTO tmp (visitor_id, page_name, visit_timestamp) VALUES (3, 'PageA', 6);
INSERT INTO tmp (visitor_id, page_name, visit_timestamp) VALUES (1, 'Home', 7);
INSERT INTO tmp (visitor_id, page_name, visit_timestamp) VALUES (1, 'PageA', 8);

Code:
SELECT      
    t.visitor_id, 
    SYS_CONNECT_BY_PATH( t.page_name, '/' ) AS path
FROM
    tmp t
START WITH  
    t.page_name = 'Home'
CONNECT BY PRIOR 
    t.visit_timestamp =
               (SELECT  MAX( visit_timestamp )
                FROM    tmp
                WHERE   visitor_id = t.visitor_id
                        AND visit_timestamp < t.visit_timestamp
                        AND t.page_name != 'Home')
ORDER BY 
    t.visitor_id, 
    t.visit_timestamp
;

outputs:
Code:
VISITOR_ID	PATH
1	/Home
1	/Home/PageA
1	/Home
1	/Home/PageA
2	/Home
2	/Home/PageB
3	/Home
3	/Home/PageA

Which you could then wrap in another select to get a count of each unique path.
 

Handor

Ars Tribunus Militum
2,513
I thought about it and wrote a solution. Several points:

First, I think you're missing something. Don't you really want a "flow prefix" count, given your requirements? What I mean is, a person who traveled A -> B -> C contributes to the overall page traffic from A -> B, even if he doesn't stop there. Your algorithm only seems to handle the case where session flows are entirely identical-- no continuing traffic. My implementation is oriented primarily around finding the prefix count, not the 'termination' count (i.e. sessions that match in their entirety), but it calculates both.

Second, this is a pure SQL approach that works on SQL Server. I have no idea whether it can be modified to work in your environment. Since string aggregation is not SQL Server's strong point, I use a recursive CTE to calculate the path. This is kind of important here, because the CTE generates not only one row for the full path per session, but all prefix paths as well. So if a visitor traveled A -> B -> C in a single session, this will output the paths 'A', 'A/B', 'A/B/C' (three rows)-- which helps us address the point above.

Third, about sessions. As you can see, you can simply use the visit_timestamp of the 'Home' visit that starts a session as the session identifier. That's what I've done here.

Fourth, this isn't really designed to be the fastest, most efficient way of doing things; it's to illustrate an approach to doing everything in SQL. Your mileage will vary. I designed the query structure in terms of the conceptual steps to approaching the problem.

Fifth, I have used your sample data, but I added a single row (as you will see) to illustrate Home -> PageA -> PageC travel.

OK, all that said, here's the code:

Code:
DECLARE @PageViews table
(
	visitor_id int,
	page_name varchar(20),
	visit_timestamp int
);

INSERT INTO @PageViews
SELECT 1, 'Home', 1 UNION ALL
SELECT 2, 'Home', 2 UNION ALL
SELECT 1, 'PageA', 3 UNION ALL
SELECT 2, 'PageB', 4 UNION ALL
SELECT 3, 'Home', 5 UNION ALL
SELECT 3, 'PageA', 6 UNION ALL
SELECT 1, 'Home', 7 UNION ALL
SELECT 1, 'PageA', 8 UNION ALL
SELECT 3, 'PageC', 9;

WITH RawSessions AS
(
	SELECT visitor_id, page_name, visit_timestamp, 
		(
			SELECT top 1 visit_timestamp 
			FROM @PageViews sub 
			WHERE sub.visitor_id = sup.visitor_id 
				AND sub.visit_timestamp <= sup.visit_timestamp 
				AND page_name = 'Home' 
			ORDER BY visit_timestamp DESC
		) session_timestamp
	FROM @PageViews sup
),
SessionSteps AS
(
	SELECT visitor_id, page_name, visit_timestamp, session_timestamp,
		ROW_NUMBER() OVER (PARTITION BY session_timestamp ORDER BY visit_timestamp) session_step
	FROM RawSessions
),
SessionPrefixes AS
(
	SELECT session_timestamp, visit_timestamp, session_step, CAST(page_name AS varchar(max)) AS session_prefix
	FROM SessionSteps
	WHERE page_name = 'Home'
	
	UNION ALL
	
	SELECT ss.session_timestamp, ss.visit_timestamp, ss.session_step, sp.session_prefix + '/' + page_name
	FROM SessionSteps ss
		INNER JOIN SessionPrefixes sp
			ON ss.session_timestamp = sp.session_timestamp AND ss.session_step = sp.session_step + 1
),
FullSessions AS
(
	SELECT * FROM SessionPrefixes sp
	WHERE NOT EXISTS 
		(
			SELECT visit_timestamp 
			FROM RawSessions 
			WHERE session_timestamp = sp.session_timestamp AND visit_timestamp > sp.visit_timestamp
		)
),
FlowCounts AS
(
	SELECT spSup.session_prefix, 
		(SELECT COUNT(*) FROM SessionPrefixes spSub WHERE spSub.session_prefix = spSup.session_prefix) AS PrefixCount,
		(SELECT COUNT(*) FROM FullSessions spSub WHERE spSub.session_prefix = spSup.session_prefix) AS TerminationCount
	FROM SessionPrefixes spSup
	GROUP BY session_prefix
)
SELECT * FROM FlowCounts

And the output:

Code:
session_prefix      PrefixCount TerminationCount
Home                4           0
Home/PageA          3           2
Home/PageA/PageC    1           1
Home/PageB          1           1

I hope this helps.
 
Status
Not open for further replies.