<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andreas Stueber on Medium]]></title>
        <description><![CDATA[Stories by Andreas Stueber on Medium]]></description>
        <link>https://medium.com/@andreas.stueber?source=rss-54caec473b7b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2oEi927CpQ9cDPuw</url>
            <title>Stories by Andreas Stueber on Medium</title>
            <link>https://medium.com/@andreas.stueber?source=rss-54caec473b7b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:34:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andreas.stueber/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[BigQuery: An efficient way to calculate averages over running windows]]></title>
            <link>https://tech-blog.goflink.com/bigquery-an-efficient-way-to-calculate-averages-over-running-windows-e1b4dd34fdfe?source=rss-54caec473b7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1b4dd34fdfe</guid>
            <category><![CDATA[sql-window-functions]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Andreas Stueber]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 14:41:04 GMT</pubDate>
            <atom:updated>2024-01-24T16:19:22.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IIFndxk9qxLNXT_A" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi, I’m Andreas, a dedicated data analytics team lead at Flink SE, the leading force in the European quick commerce industry. At Flink, we understand the critical role that data plays in driving our business forward. In this fast-paced sector, leveraging data effectively is not just an advantage - it’s a necessity.</p><p>In my articles, I’ll be writing about some of the challenges we tackle and the solutions we come up with. Our tech stack involves Bigquery, Looker, dbt, Airlflow, and Fivetran, among others.</p><p><strong>In this article, you will learn how to use BigQuery <em>ARRAYs</em> to overcome some limitations with classical window functions.</strong></p><h3>The Problem</h3><p>Suppose you’re an analyst in a grocery delivery company, eager to identify customer-preferred products. Analyzing products’ re-ordering behavior can reveal high-demand items. You aim to determine, each month, which products have the highest re-order rates over the past three months.</p><p>What we want is a table that looks just like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SLu3GfYvHwUOomlQPc9Y8Q.png" /></figure><p>In the upcoming sections, I’ll highlight the challenges in obtaining this data and propose a viable solution.</p><p>Let’s start by examining some preliminary data.</p><h3>First things first: calculate the order frequency</h3><p>Assume we have an orders table with a customer_id linked to each product order. A query to calculate the days since the last order might look as follows:</p><pre>select<br>    customer_id,<br>    order_date,<br>    product_name,<br>    date_diff(<br>        order_date,<br>        lag(order_date) over (partition by customer_id, product_name<br>                                  order by order_date),<br>        day<br>    ) as days_since_last_order<br><br>from orders<br><br>order by<br>    customer_id, product_name, order_date</pre><p>This query yields results for the computed days since a product’s last order:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hq659s9GPvc31DKAtdOY5g.png" /><figcaption>Computed days since last order of a product</figcaption></figure><h3>Facing the first problem</h3><p>Given the data, an intuitive step is to calculate a monthly average of days_since_last_order(or, optimally, an average over the last 3 months using a window function).</p><p>Let’s start simply by calculating the average ‘days_since_last_order’ per month, customer, and product:</p><pre>with<br>order_frequency as (<br>  select<br>    customer_id,<br>    order_date,<br>    product_name,<br>    date_diff(<br>      order_date,<br>      lag(order_date) over (partition by customer_id, product_name<br>                                order by order_date),<br>      day<br>    ) as days_since_last_order<br><br>  from orders<br>),<br><br>order_frequency_per_month as (<br>  select<br>    date_trunc(order_date, month) as order_month,<br>    customer_id,<br>    product_name,<br>    avg(days_since_last_order) as avg_reordering_days<br><br>  from order_frequency<br><br>  group by<br>    1,2,3<br><br>  order by <br>    2,3,1<br>)<br>select *<br>from order_frequency</pre><p>This query returns data on the average days to re-order a product per month:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*0JPOtfe_D_3-NN1m7VH0Ig.png" /><figcaption>Average days to re-order a product — per month</figcaption></figure><p>However, a significant issue arises: customers don’t purchase the product every month. For a given month, we want to calculate the average days between orders within the previous 3 months.</p><p>As we see in the example month of <strong>2022–06–01</strong>, we are missing May sales. This inconsistency means using window functions is challenging, as they typically relate to preceding rows. We can’t use sth. like the following code snippet, as we would accidentally calculate the average over a timeframe between November 2021 and April 2022, which is not the last 3 months before June 2022.</p><p>(It is also not a good approach, as we compute the average over averages, but let’s use this example for the sake of simplicity)</p><pre>select<br>  *,<br>  avg(avg_reordering_days) over win as avg_reordering_days_last_3m<br>from order_frequency_per_month<br><br>window<br>  win as (<br>    partition by <br>      customer_id,<br>      product_name<br>    order by<br>      order_month<br>    rows between <br>      3 preceeding and 1 preceeding</pre><p>So, What’s Next?</p><h3>BigQuery Arrays to the Rescue</h3><p>From my experience, flat tables are often preferred by data consumers (the business analysts) and producers (the analytics engineers or data analysts) alike. Still, one of the greatest and most overlooked features of BigQuery is how elegant and efficient data can be manipulated using arrays.</p><p>To achieve our big goal of calculating the re-ordering frequency of a product over the last 3 months, let’s proceed step by step, with examples:</p><p><strong>Step 1) Aggregate the data (again) per customer, product, and order month</strong></p><p>In this first step, we aggregate the data again, but this time using the array_agg() function instead of avg(). This provides us with the list of orders per month and their pre-calculated days_since_last_order</p><pre>with<br>order_frequency as (<br>  select<br>    customer_id,<br>    order_date,<br>    product_name,<br>    date_diff(<br>      order_date,<br>      lag(order_date) over (partition by customer_id, product_name<br>                                order by order_date),<br>      day<br>    ) as days_since_last_order<br><br>  from orders<br>),<br><br>order_frequency_per_month as (<br>  select<br>    date_trunc(order_date, month) as order_month,<br>    customer_id,<br>    product_name,<br>    array_agg(struct(order_date, days_since_last_order)) as reordering_data<br><br>  from order_frequency<br><br>  group by<br>    1,2,3<br>  order by <br>    2,3,1<br>)</pre><p>This is already a good first step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMENGoTZEcgkzLzEDwAFKQ.png" /></figure><p><strong>Step 2) Combine the arrays with the ordering data of the previous 3 months</strong></p><p>In this step, we want to create a new ARRAY-field, that holds the data we need (the order dates and times between them within the last 3 months). For this, we can use BigQuery&#39;s handy array_concat()<em> </em>function. Unfortunately, if one of the concatenated ARRAYs is NULL then the whole field will be NULL. This is especially problematic at the beginning of a time series with no previous months, but we can handle this with a coalesce() statement with an empty ARRAY (defined as [] ).</p><p>Let’s see what the related code would look like:</p><pre>with<br><br>...<br><br>order_frequency_last_3_month as (<br>  select <br>    * except(reordering_data),<br>    -- concat all order dates of the last 3 months into 1 array<br>    array_concat(<br>      -- if a array is empty, the whole array_concat is empty<br>      ifnull(lag(reordering_data,1) over win, []), <br>      ifnull(lag(reordering_data,2) over win, []), <br>      ifnull(lag(reordering_data,3) over win, []))   as last_3m_order_dates_per_month,<br>  <br>  from order_frequency_per_month<br><br>  window<br>    win as (<br>      partition by<br>        customer_id,<br>        product_name<br>      order by <br>        order_month<br>    )<br>)<br>select *<br>from order_frequency_last_3_month</pre><p>What happens here:</p><p>We create a partition called win, which we define to be per customer_id and product_name. We use BigQuerys lag()function to fetch the reorder_data-ARRAYs of the last 3 rows (which are ideally the last 3 months, but unfortunately we saw, that this is not always the case). Lastly, we use the array_concat() function to combine the last 3 months&#39; ARRAYs.</p><p>So far so good:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WBHa-cu0EGN8sy0o1eAc0A.png" /><figcaption>Combined BigQuery ARRAYs of the previous 3 months of order data</figcaption></figure><p><strong>Step 3) Filter the ARRAYs and calculate the final metric</strong></p><p>In this final step, we treat the ARRAY as a regular table within our main table, selecting and averaging days_since_last_order for orders placed within the previous 3 months.</p><pre><br>with<br><br>...<br><br>final_metric as (<br><br>  select <br>    *,<br>    (<br>      select avg(arr.days_since_last_order) as avg_days_since_last_order<br>      <br>      from unnest(last_3m_order_dates_per_month) as arr<br>      <br>      where<br>            arr.order_date &lt; orders.order_month<br>        and arr.order_date &gt;= date_sub(orders.order_month, interval 3 month)<br>        and arr.days_since_last_order is not null<br><br>    ) as avg_reorder_days_last_3_month<br><br>  from order_frequency_last_3_month as orders<br>)<br>select *<br>from final_metric</pre><p>Et voilá — here it is: the average re-ordering days of the last 3 months</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kho7KcH9zbrKoDbULy85iQ.png" /></figure><p>Find the complete here the complete code <a href="https://gist.github.com/astueber/275c62bd55d1c0a6c9d38ad6274a7292">here in Github</a>.</p><h3>Summary</h3><p>So, what did we dive into today? We explored how BigQuery’s ARRAY (and STRUCT) data types aren’t just cool features — they’re game-changers. They offer a fresh take on the limitations of traditional window functions, giving you more control and flexibility in selecting and aggregating data. Plus, they’re fantastic for debugging SQL logic — you can easily check what data you’re working with at each step. And though we didn’t dig into it this time, keep in mind that ARRAYs aren’t just about neat code — they can also be kinder to your wallet by cutting down your Google Cloud costs by reducing required computing power compared to window functions. Talk about a win-win!</p><p>Hope you enjoyed this read!</p><p>If you’re into stuff like BigQuery, Looker, dbt, and all things data science, feel free to follow me for more insights. Better yet, if you’re looking to dive into innovative solutions hands-on, why not <a href="https://careers.smartrecruiters.com/Flink3/joinus">join our team at Flink</a>? We’re always on the lookout for fresh talent to join us in Berlin or Amsterdam. <a href="https://careers.smartrecruiters.com/Flink3/joinus">Check out our career opportunities</a> and let’s make some data magic together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1b4dd34fdfe" width="1" height="1" alt=""><hr><p><a href="https://tech-blog.goflink.com/bigquery-an-efficient-way-to-calculate-averages-over-running-windows-e1b4dd34fdfe">BigQuery: An efficient way to calculate averages over running windows</a> was originally published in <a href="https://tech-blog.goflink.com/">Flink</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>