Skip to content
Advertisement

Order count per ID and calculate time between orders in BigQuery

I am working with customer purchase data and am trying to write a query in Google BigQuery that sorts all purchases by date and adds a purchase/order count per customer (order_count). Also, I would like to calculate a time-delay (in days) between the orders of one customer (purchase_latency). My query currently looks like this:

The result including “order_count” and “purchase_latency” should look like the following:

How would I add the numbering for “order_count” as well as the calculation for “purchase_latency”?

Thank you very much!

Advertisement

Answer

You can use window functions:

  • to enumerate the orders of each customer by increasing purchase date, you can use row_number()

  • lag() retrieves the date of the “previous” purchase, and you can compute the difference with the current date with date_diff():

So:

Note: I would highly recommend prefixing all the column names in the query with the (alias of the) table they belong to; this makes the query unambiguous, and much easier to follow.

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