Skip to content
Advertisement

How to pull a list of all visitor_ids that generated more than $500 combined in their first two sessions in the month of January 2020?

Tables:

  1. Sessions

    • session_ts
    • visitor_id
    • vertical
    • session_id
  2. Transactions

    • session_ts
    • session_id
    • rev_bucket
    • revenue

Currently have the following query (using SQLite):

I’m having trouble identifying the first two sessions that combine for $500. Open to any feedback and simplifying of query. Thanks!

Advertisement

Answer

You can use window functions and aggregation:

The subquery joins the two tables, filters on the target month (note that using half-open interval predicates is more efficient than applying date functions on the date column), and ranks each row within groups of visits of the same customer.

Then, the outer query filters on the first two visits per visitor, aggregates by visitor, computes the corresponding revenue, and filters it with a having clause.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement