Calculating Difference from Beginning/First Row in SQL

How to find the first or last value in your query result and use it in the current row?

This question commonly comes up with calculating growth rates, where you want to see the performance in different time frames, year-to-date and month-to-date. Other uses are:

  • How much gap are we seeing from the current row to the last value in the query? Useful for sales projections and meeting quotas.

Consider a table of stock pices:

dt price
2013-01-01 70
2013-01-02 71
2013-01-03 72
2013-02-01 73
2013-02-02 74
2013-02-03 75

First value in the entire table

If you simple the first value in the entire table, the first_value is what you're looking for. The window definition excludes any parameters (the OVER clause) and so your window is over the entire table:

select dt,
       price,
       first_value(price) over ()
from trades;
dt price first_value
2013-01-01 70 70
2013-01-02 71 70
2013-01-03 72 70
2013-02-01 73 70
2013-02-02 74 70
2013-02-03 75 70

First value in the partition

You can start to fill in the window parameters to get just the first value in the current partition. In this case, we can find the first value for the month which can be used to compute a differnce or percentage growth to date.

select dt,
    price,
    first_value(price) over (partition by date_trunc('month', dt))
from trades;
dt price first_value
2013-01-01 70 70
2013-01-02 71 70
2013-01-03 72 70
2013-02-01 73 73
2013-02-02 74 73
2013-02-03 75 73

Also, last_value

Just like the first_value window function, you also have access to the last_value function that picks the last value in the current partition.


👋 No fuss, just SQL We are open sourcing everything from the experience working with our agency clients. They spend thousands of dollars to get this level of detailed analysis – which you can now get for free. We send one update every week. Join 400+ data analysts who are leveling up with our recipes. 👊

No spam, ever! Unsubscribe any time. See past emails here.

results matching ""

    No results matching ""