MySQL LAG Function Explanation

Overview

The LAG function in MySQL is a window function that allows you to access data from a previous row within the same result set. It is particularly useful for calculating differences between sequential rows, such as in time series analysis.

SQL Query Explanation

SELECT ROUND(AVG(daily_increase), 4) AS avg_daily_increase
FROM (
    SELECT dt1, (price - LAG(price) OVER (ORDER BY dt1)) AS daily_increase
    FROM binance.klines_1d
    WHERE dt1 >= CURDATE() - INTERVAL %d DAY
) AS price_changes
WHERE daily_increase IS NOT NULL;

1. Inner Query

2. Filtering Dates

3. Outer Query