<?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 Alex Yeskov on Medium]]></title>
        <description><![CDATA[Stories by Alex Yeskov on Medium]]></description>
        <link>https://medium.com/@ayeskov?source=rss-c32af618e531------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BzejRBHMkB6roW3B3e3LLA.jpeg</url>
            <title>Stories by Alex Yeskov on Medium</title>
            <link>https://medium.com/@ayeskov?source=rss-c32af618e531------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:10:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayeskov/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[SQL Window Functions Tutorial for Business Analysis]]></title>
            <link>https://medium.com/cube-dev/sql-window-functions-tutorial-b5075b87d129?source=rss-c32af618e531------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5075b87d129</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[revenue]]></category>
            <category><![CDATA[business-analysis]]></category>
            <dc:creator><![CDATA[Alex Yeskov]]></dc:creator>
            <pubDate>Thu, 07 Dec 2017 14:38:33 GMT</pubDate>
            <atom:updated>2017-12-07T15:25:20.557Z</atom:updated>
            <content:encoded><![CDATA[<h4>The most popular business problems solved with SQL</h4><p>Any person that has worked with data analytics has had a bad day when they sighed over a problem that was intuitively simple but practically hard to crack using pure SQL.</p><p>What is the revenue growth month over month and running total revenue? Can we trust the metric, or does the data have some accidental duplicates that affect it? What are the top N orders for every month? What is the repeat purchase behavior? All these questions have to be translated from business language to programming language.</p><p>An intuitive solution in a countless number of cases like these is, “If only I could just loop over the results of my query I would be able to get the answer right away.” This opens a door to a world of workarounds: writing complex joins, data ending up in another spreadsheet, using procedural extensions of SQL, or even moving data processing outside the database. Not all alternatives are viable, others are just ugly.</p><blockquote><em>At the same time, there’s a pure SQL implementation called “window functions” that is very readable, performant, and easy to debug.</em></blockquote><p>In this SQL window functions tutorial, we will describe how these functions work in general, what is behind their syntax, and show how to answer these questions with pure SQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzaWDzG9BnL9gE5GP-yCcA.jpeg" /></figure><h3>Learn by doing</h3><p>For people unfamiliar with SQL window functions, the <a href="http://docs.aws.amazon.com/redshift/latest/dg/c_Window_functions.html">official database documentation</a> can be hard to decipher, so we’ll go with real examples, starting from very basic queries and increasing the degree of complexity.</p><p>Questions that were listed in the introduction above are real business questions that practically any company faces, and window functions are a huge help with answering them. Imagine we have the following table of orders:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hTBBC_Akoa6KWBLmQ8qmA.png" /><figcaption>Data visualized with <a href="https://statsbot.co/solutions/product-analytics?utm_source=blog&amp;utm_medium=article&amp;utm_campaign=windows">Statsbot</a></figcaption></figure><p>This dataset is very simple and small, however it is sufficient to illustrate the power of SQL window functions. Let’s start with the revenue growth.</p><h3>Revenue growth</h3><p>In business terms, revenue growth in month M1 is calculated as:</p><p><em>100*(m1-m0)/m0</em></p><p>where <em>m1</em> is the revenue in the given month and <em>m0</em> is the revenue in the previous month. So, technically we would need to find what the revenue is for each month and then somehow relate every month to the previous one to be able to do the calculation above. A very easy way to do this would be to calculate the monthly revenue in SQL:</p><pre>SELECT<br>date_trunc(‘month’,datetime) as month,<br>sum(amount) as revenue<br>FROM orders<br>GROUP BY 1<br>ORDER BY 1</pre><p>then copy the output into the spreadsheet and use a formula to produce a growth metric:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/0*0qx7LmSNsS3UlPFh." /></figure><p>When you copy the formula from cell C3 to cell C4 and so on, references are automatically shifted down, that’s what spreadsheets are good at. But what if you’d like to have this metric as a part of a nice dashboard that is fed by data coming directly from the database? Such tools as <a href="https://statsbot.co/solutions/product-analytics?utm_source=blog&amp;utm_medium=article&amp;utm_campaign=windows"><strong>Statsbot</strong></a> can help you with that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wQzsPi9P1RCY4xpk." /><figcaption>Data visualized with <a href="https://statsbot.co/solutions/product-analytics?utm_source=blog&amp;utm_medium=article&amp;utm_campaign=windows">Statsbot</a></figcaption></figure><p>In this case, a spreadsheet is definitely not what you want to end up with. Let’s try to calculate this in SQL. Without window functions, a query that gets you the final result would look like this:</p><pre>WITH<br>monthly_revenue as (<br>    SELECT<br>    date_trunc(‘month’,datetime)::date as month,<br>    sum(amount) as revenue<br>    FROM orders<br>    GROUP BY 1<br>)<br>,prev_month_revenue as (<br>    SELECT<br>    t1.*,<br>    t2.revenue as prev_month_revenue<br>    FROM monthly_revenue t1<br>    LEFT JOIN monthly_revenue t2<br>    ON datediff(month,t2.month,t1.month)=1<br>)<br>SELECT *,<br>round(100.0*(revenue-prev_month_revenue)/prev_month_revenue,1) as revenue_growth<br>FROM prev_month_revenue<br>ORDER BY 1</pre><p>You’d have to calculate monthly revenue, then get the result of the previous month using self-join and use it in the final formula. The logic is broken down into 3 steps for clarity. You can’t break it down further, but even so the second step can be quite confusing.</p><p>What you have to keep in mind about <em>datediff</em> is that that the minuend (i.e. what you subtract from) is the third parameter of the function and the subtrahend (i.e. what you subtract) is the second parameter. I personally think that’s a bit counterintuitive for subtraction, and the self join concept itself is not basic. There’s actually a much better way to express the same logic:</p><pre>WITH<br>monthly_revenue as (<br>    SELECT<br>    date_trunc(‘month’,datetime)::date as month,<br>    sum(amount) as revenue<br>    FROM orders<br>    GROUP BY 1<br>)<br>,prev_month_revenue as (<br>    SELECT *,<br>    lag(revenue) over (order by month) as prev_month_revenue<br>    FROM monthly_revenue<br>)<br>SELECT *,<br>round(100.0*(revenue-prev_month_revenue)/prev_month_revenue,1) as revenue_growth<br>FROM prev_month_revenue<br>ORDER BY 1</pre><p>Let’s break down the <em>lag(</em>… line of code:</p><ul><li><em>lag </em>is a window function that gets you the previous row</li><li><em>revenue</em> is the expression of what exactly you would like to get from that row</li><li><em>over (order by month)</em> is your window specification that tells how exactly you would like to sort the rows to identify which row is the previous one (there’s plenty of options). In our case, we told the database to get the previous month’s row for every given month.</li></ul><p>This is a generic structure of all SQL window functions: function itself, expression and other parameters, and window specification:</p><pre><em>function (expression, [parameters]) </em>OVER<em> (window specification)</em></pre><p>It is very clean and powerful and has countless opportunities. For example, you can add <em>partition by</em> to your window specification to look at different groups of rows individually:</p><pre>WITH<br>monthly_revenue as (<br>    SELECT<br>    date_trunc(‘month’,datetime)::date as month,<br>    state,<br>    sum(amount) as revenue<br>    FROM orders<br>    GROUP BY 1,2<br>)<br>,prev_month_revenue as (<br>    SELECT *,<br>    lag(revenue) over (partition by state order by month) as prev_month_revenue<br>    FROM monthly_revenue<br>)<br>SELECT *,<br>round(100.0*(revenue-prev_month_revenue)/prev_month_revenue,1) as revenue_growth<br>FROM prev_month_revenue<br>ORDER BY 2,1</pre><p>Calculating revenue by state in the first subquery and updating the window specification to take the new grouping into account, you can look at each state individually and see what the revenue growth by state is.</p><blockquote>Partitions are extremely useful when you need to calculate the same metric over different segments.</blockquote><h3>Running total</h3><p>Another common request is to calculate running total over some period of time. This is the sum of the current element and all previous elements, for example, this is how the running total monthly revenue would look in our dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*yleo9Y_Ut9PE3uukuL9Cew.png" /><figcaption>Data visualized with <a href="https://statsbot.co/solutions/product-analytics?utm_source=blog&amp;utm_medium=article&amp;utm_campaign=windows">Statsbot</a></figcaption></figure><p>And the query to get this is below:</p><pre>WITH<br>monthly_revenue as (<br>    SELECT<br>    date_trunc(‘month’,datetime)::date as month,<br>    sum(amount) as revenue<br>    FROM orders<br>    GROUP BY 1<br>)<br>SELECT *,<br>sum(revenue) over (order by month rows between unbounded preceding and current row) as running_total<br>FROM monthly_revenue<br>ORDER BY 1</pre><p>The new thing here is the <em>rows between unbounded preceding and current row</em> part that is called “frame clause.” It’s a way to tell you which subset of other rows of your result set you’re interested in, relative to the current row. The general definition of the frame clause is:</p><pre>rows between<em> frame_start </em>and<em> frame_end</em></pre><p>where <em>frame_start </em>can be one of the following:</p><ul><li><em>unbounded preceding</em> which is “starting from the first row or ending on the last row of the window”</li><li><em>N preceding</em> is N rows you’re interested in</li><li><em>current row</em></li></ul><p>and <em>frame_end </em>can be:</p><ul><li><em>unbounded following</em> which is “starting from the first row or ending on the last row of the window”</li><li><em>N following</em> is N rows you’re interested in</li><li><em>current row</em></li></ul><p>It’s very flexible, except that you have to make sure the first part of <em>between</em> is higher than the second part, i.e. <em>between 7 preceding and current row</em> is totally fine, <em>between 7 preceding and 3 preceding </em>is fine too, but <em>between 3 preceding and 7 preceding</em> would throw an error. You can sum, count, and average values within the selected window. You can see a few examples in the query below:</p><pre>SELECT<br> *<br>,sum(amount) over () as amount_total<br>,sum(amount) over (order by order_id rows between unbounded preceding and current row) as running_sum<br>,sum(amount) over (partition by customer_id order by datetime rows between unbounded preceding and current row) as running_sum_by_customer<br>,avg(amount) over (order by datetime rows between 5 preceding and current row) as trailing_avg<br>FROM orders<br>ORDER BY 1</pre><p>Every combination makes sense for particular use cases:</p><ul><li><em>amount_total</em> is specified without a window and returns the entire total of $3400. Use it when you want to get the total in the same query as individual rows without grouping and joining back the grouped result.</li><li><em>running_sum</em> is the running total. Use it when you want to see how some variable such as revenue or website visits is accumulated over a period of time.</li><li><em>running_sum_by_customer</em> is the same as above but broken down by segment (you can see how revenue from each individual customer grows, and on bigger data it can be cities or states).</li><li><em>trailing_avg</em> shows the average amount of the last 5 orders. Use trailing average when you want to learn the trend and disguise volatility.</li></ul><p>The ordering is critical here since the database needs to know how to sum the values. The result can be completely different when different ordering is applied. The picture below shows the result of the query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w3CJZisscCgRIwo6H6JZqA.png" /><figcaption>Data visualized with <a href="https://statsbot.co/solutions/product-analytics?utm_source=blog&amp;utm_medium=article&amp;utm_campaign=windows">Statsbot</a></figcaption></figure><p>The arrow next to <em>running_sum</em> tells us how the total amount is accumulated over time. The colored arrows next to <em>running_sum_by_customer</em> interconnect orders done by the same customer and the values show the total order amount of the given customer at the point of every order. Finally, the grey brackets next to <em>trailing_avg</em> reference the moving window of the last 5 rows.</p><h3>Dealing with duplicate data</h3><p>If you paid attention to the dataset you would probably notice that both orders for customer D on 02–05 have the same order_id=5 which doesn’t look right. How did this happen? It turns out that the original order was $250, then the customer decided to spend $50 more. The new record was inserted but the old record was not deleted. Such things happen in one or another table.</p><p>A long term solution in this case is to rectify the existing data flows and increase data awareness among developers, and what you can do right away is roll your sleeves up and clean the mess on your side:</p><pre>SELECT *<br>FROM (<br>    SELECT *,<br>    row_number() over (partition by order_id order by datetime desc)<br>    FROM orders<br>)<br>WHERE row_number=1</pre><p>That would get you all order records except one that you’d like to filter out. Let’s review the function that allows us to do so: <em>row_number() </em>returns the incremental counter of the row within the given window: 1,2,3, etc. It doesn’t take any parameters, that’s why it ends with empty brackets. The given window here is a set of rows that share a common order_id (<em>partition by … </em>is what separates these sets from each other), sorted by <em>datetime</em> descending, so the intermediary result of the subquery in the middle looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R9UrY6fGZUmOR0pvr6ioQw.png" /><figcaption>Data visualized with <a href="https://statsbot.co/solutions/product-analytics?utm_source=blog&amp;utm_medium=article&amp;utm_campaign=windows">Statsbot</a></figcaption></figure><p>Every partition here is represented by a single row, except order_id=5. Inside the partition, you sorted the rows by datetime descending, so the latest row gets 1 and the earlier row gets 2. Then you filter only rows that have 1 to get rid of duplicates.</p><p>This is very useful for all sorts of duplicate problems. You might see that duplicates inflate the revenue number, so to calculate correct metrics we have to clean them out by combining the duplicate filtering query with the revenue growth query like this:</p><pre>WITH<br>orders_cleaned as (<br>    SELECT *<br>    FROM (<br>        SELECT *,<br>        row_number() over (partition by order_id order by datetime desc)<br>        FROM orders<br>    )<br>    WHERE row_number=1<br>)<br>,monthly_revenue as (<br>    SELECT<br>    date_trunc(‘month’,datetime)::date as month,<br>    sum(amount) as revenue<br>    FROM orders_cleaned<br>    GROUP BY 1<br>)<br>,prev_month_revenue as (<br>    SELECT *,<br>    lag(revenue) over (order by month) as prev_month_revenue<br>    FROM monthly_revenue<br>)<br>SELECT *,<br>round(100.0*(revenue-prev_month_revenue)/prev_month_revenue,1) as revenue_growth<br>FROM prev_month_revenue<br>ORDER BY 1</pre><p>Now the data is clean and the revenue and growth metrics are correct. To avoid using orders_cleaned step in every query, you can create a view and use it as a table reference in other queries:</p><pre>CREATE VIEW orders_cleaned AS<br>SELECT order_id, customer_id, state, “datetime”, amount<br>FROM (<br>    SELECT *,<br>    row_number() over (partition by order_id order by datetime desc)<br>    FROM orders<br>)<br>WHERE row_number=1</pre><p>Besides filtering duplicates, window partitions are very useful when you need to identify top N rows in every group.</p><h3>Top N rows in every group</h3><p>Finding top rows in every group is a typical task for a data analyst. Finding out who your best customers are and reaching out to them is a good way to know what people especially like about your company and make it a standard. It is equally useful for employees, as leaderboards can be very good motivation for any team in the company. Let’s see how it works. Considering our dataset is tiny, let’s get the top 2 orders for every month:</p><pre>WITH<br>orders_ranked as (<br>    SELECT<br>    date_trunc(‘month’,datetime)::date as month,<br>    *,<br>    row_number() over (partition by date_trunc(‘month’,datetime) order by amount desc, datetime)<br>    FROM orders_cleaned<br>)<br>SELECT *<br>FROM orders_ranked<br>WHERE row_number&lt;=2<br>ORDER BY 1</pre><p>The intermediary result of the <em>orders_ranked</em> statement would look like this (rows that appear in the final result are highlighted):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*woVn1wyZUiCUjIdqPvziGQ.png" /><figcaption>Data visualized with <a href="https://statsbot.co/solutions/product-analytics?utm_source=blog&amp;utm_medium=article&amp;utm_campaign=windows">Statsbot</a></figcaption></figure><blockquote>You can use any expression to separate partitions in window specification, not only column name (here we separated them by month, every partition is highlighted by its own color).</blockquote><p>There are orders with the same month and amount, like order_id=1 and order_id=3, so we decided to resolve this by picking up the earliest order, adding <em>datetime</em> column to the sorting. If you’re interested in pulling both rows in case of conflict you can use <em>rank</em> function instead of <em>row_number</em>.</p><h3>Repeat purchase behavior</h3><p>Repeat purchase behavior is the key for a successful business, and investors totally love companies that can retain customers and make them spend more and more. We can translate this to a more precise data question: what is the repeat purchase rate and the typical difference between the first order and the second order amount? That would be expressed as:</p><pre>WITH<br>customer_orders as (<br>    SELECT *,<br>    row_number() over (partition by customer_id order by datetime) as customer_order_n,<br>    lag(amount) over (partition by customer_id order by datetime) as prev_order_amount<br>    FROM orders_cleaned<br>)<br>SELECT<br>round(100.0*sum(case when customer_order_n=2 then 1 end)/count(distinct customer_id),1) as repeat_purchases,<br>avg(case when customer_order_n=2 then 1.0*amount/prev_order_amount end) as revenue_expansion<br>FROM customer_orders</pre><p>The result of the intermediary <em>customer_orders</em> statement would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VbUxnh-xGgGtYYw4Gxheuw.png" /><figcaption>Data visualized with <a href="https://statsbot.co/solutions/product-analytics?utm_source=blog&amp;utm_medium=article&amp;utm_campaign=windows">Statsbot</a></figcaption></figure><p>Every customer’s partition is highlighted by its own color. The brackets next to <em>customer_id</em> outline our partitions, the arrows next to <em>datetime</em> show sorting direction, the arrows that point to <em>amount</em> values show where <em>prev_order_amount</em> values come from, and <em>customer_order_n</em> values for repeat purchases are underlined. Since customers D, E, and F have only one order they are out of the analysis.</p><p>The final result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*xjRCEjrHCGgEClSZvAQc_w.png" /><figcaption>Data visualized with <a href="https://statsbot.co/solutions/product-analytics?utm_source=blog&amp;utm_medium=article&amp;utm_campaign=windows">Statsbot</a></figcaption></figure><p>This time we partitioned by customer_id to isolate sets of order rows that belong to the same customer, and identified the row order and the previous row’s amount value. In the final query, we have used conditional aggregates to calculate desired metrics which tell us that half of customers buy again and they spend almost twice as much on the second order. Imagine it’s not a dummy dataset, what a great business would that be!</p><h3>Wrap up</h3><p>As you have seen in our tutorial, SQL window functions are a powerful concept that allows advanced calculations. A typical window function consists of expression and window specification with optional partitioning and frame clause, and the opportunities to slice, smooth, interconnect, and deduplicate your data are truly boundless. There are plenty of interesting use cases where these functions give a great value. We’ll continue talking about them in the next few tutorials. Stay tuned!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F0d3e8c%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2F0d3e8c%2F&amp;image=https%3A%2F%2Fupscri.be%2Fmedia%2Fform.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/02231cd5403151a2a463e36cc3b88462/href">https://medium.com/media/02231cd5403151a2a463e36cc3b88462/href</a></iframe><h3>YOU’D ALSO LIKE:</h3><ul><li><a href="https://blog.statsbot.co/customer-retention-analysis-93af9daee46b">A Guide for Customer Retention Analysis with SQL</a></li><li><a href="https://blog.statsbot.co/sql-queries-for-funnel-analysis-35d5e456371d">SQL Queries for Funnel Analysis</a></li><li><a href="https://blog.statsbot.co/how-to-reduce-churn-rate-by-27-by-handling-stripe-failed-payments-e75892f8956c">How to Reduce Churn Rate By Handling Stripe Failed Payments</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5075b87d129" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cube-dev/sql-window-functions-tutorial-b5075b87d129">SQL Window Functions Tutorial for Business Analysis</a> was originally published in <a href="https://medium.com/cube-dev">Cube Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>