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.