LAG
Function ExplanationThe 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.
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;
Purpose: To calculate the daily price increase by comparing the current day's price (price
) with the previous day's price.
LAG(price) OVER (ORDER BY dt1)
:
LAG
function retrieves the value of the price
column from the previous row.ORDER BY dt1
clause ensures that the rows are processed in chronological order based on the dt1
(date) column.price - LAG(price) OVER (ORDER BY dt1)
:
daily_increase
.WHERE dt1 >= CURDATE() - INTERVAL %d DAY
:
%d
days from the current date.Purpose: To calculate the average of the daily price increases.
ROUND(AVG(daily_increase), 4)
:
AVG
) of the daily increases and rounds the result to four decimal places.WHERE daily_increase IS NOT NULL
:
daily_increase
is NULL
to ensure that the average is calculated only on valid values.