Skip to content
Advertisement

How do I create cohorts of users from month of first order, then count information about those orders in SQL?

I’m trying to use SQL to:

  1. Create user cohorts by the month of their first order
  2. Sum the total of all the order amounts bought by that cohort all-time
  3. Output the cohort name (its month), the cohort size (total users who made first purchase in that month), total_revenue (all order revenue from the users in that cohort), and avg_revenue (the total_revenue divided by the cohort size)

Please see below for a SQL Fiddle, with sample tables, and the expected output:

http://www.sqlfiddle.com/#!15/b5937

Thanks!!

Users Table

Orders Table

Desired Output

Advertisement

Answer

You can find the minimum date for every user and aggregate for them. Then you can aggregate for every such date:

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