Next and Previous Rows
Learn how to get values from next or previous rows in SQL.
We'll cover the following...
Overview
In many types of analysis, it is often necessary to compare a row to the next or previous rows. For example, calculating the change in a stock price, calculating the increase or decrease of a certain measure, and so on. Window functions are a great fit for this type of analysis.
Given our temperature data set, say we want to find the temperature change on each day. To do that, for each day, we need to find the temperature of the previous day:
Press + to interact
SELECTt_outer.*,(-- Find the last temperature in the same citySELECTtemperatureFROMtemperatures t_innerWHERE-- Same cityt_inner.city = t_outer.city-- Days prior to "outer" current dateAND t_inner.day < t_outer.dayORDER BYt_inner.day DESCLIMIT1) previous_temperatureFROMtemperatures t_outerORDER BYt_outer.city,t_outer.day;
The query uses a subquery to find the previous temperature in each city on each day. The subquery finds all the temperatures in the same city in days prior to the current row in the outer query. It then sorts ...
Access this course and 1400+ top-rated courses and projects.