Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need BigQuery SQL query to collect time on page from Google Analytics data

can anyone help with a BIgQuery SQL query to extract the time on page for a specific page from Google Analytics data please?

For every visitorId who has visited a particular page I would like the time on page for that page. This is so that I can calculate the median time on page rather than the mean.

I'm assuming that the visitorId, hits.hitsNumber and hits.time dimensions will be needed. Also that somehow the hits.time for the hit where the page was viewed will need to be subtracted from the hits.time of the following hit.

Any help much appreciated.

like image 843
Pete Blakemore Avatar asked Oct 12 '16 14:10

Pete Blakemore


People also ask

How does BigQuery calculate average time on page?

Time on page is calculated as the delta between the time of the current pageview and the time of the following pageview. In case no pageviews follow the current one, the time of the last interactive event is used to calculate the delta.

Can you use SQL in Google Analytics?

Google Analytics and SQL: A Powerful Combo Google Analytics is a powerful tool. However, you can also export information from GA to create SQL reports that will give you even more insight into your data. And if you've analyzed this article well, you already know that learning SQL will pay off for sure.


1 Answers

Try this:

SELECT 
  fullVisitorId,
  hits.page.hostname,
  hits.page.pagePath,
  hits.hitNumber,
  hits.time,
  nextTime,
  (nextTime - hits.time) as timeOnPage
FROM(
  SELECT
    fullVisitorId, 
    hits.page.hostname,
    hits.page.pagePath,
    hits.hitNumber,
    hits.time,
    LEAD(hits.time, 1) OVER (PARTITION BY fullVisitorId, visitNumber ORDER BY hits.time ASC) as nextTime
  FROM [PROJECTID:DATASETID.ga_sessions_YYYYMMDD]
  WHERE hits.type = "PAGE"
)

The key to this code is the LEAD() function, which grabs the specified value from the next row in the partition, based on the PARTITION BY and ORDER BY qualifiers.

Hope that helps!

like image 130
andre622 Avatar answered Sep 22 '22 06:09

andre622