Im between cherry

MySQL | LEAD, LAG 윈도우 함수 본문

데이터분석/SQL

MySQL | LEAD, LAG 윈도우 함수

meal 2020. 8. 30. 15:03

1. MySQL LEAD Function

LEAD()함수는 현재 행에서 여러 행을 보고 해당 행의 데이터에 액세스 할 수 있는 윈도우 함수입니다.

LAG()함수와 비슷하며, LEAD()기능은 현재 행과 동일한 결과 집합 내의 후속 행과의 차이를 계산하기위해 매우 유용하다.

LEAD(<expression>[,offset[, default_value]]) OVER (
    PARTITION BY (expr)
    ORDER BY (expr)
)

 LEAD()함수는 정렬된 파티션 expression의 offset-th행에서의 값을 반환합니다 .

 

예시) orders and customers tables 

 

SELECT 
    customerName,
    orderDate,
    LEAD(orderDate,1) OVER (
        PARTITION BY customerNumber
        ORDER BY orderDate ) nextOrderDate
FROM 
    orders
INNER JOIN customers USING (customerNumber);

https://www.mysqltutorial.org/mysql-window-functions/mysql-lead-function/

 

MySQL LEAD Function By Practical Examples

This tutorial shows you how to use the MySQL LEAD() function to access data from a subsequent row from the current row in the same result set.

www.mysqltutorial.org

 

2. MySQL LAG Function

LAG()함수는 여러 행을 되돌아보고 현재 행에서 해당 행의 데이터에 액세스 할 수 있는 윈도우 함수입니다.

LAG(<expression>[,offset[, default_value]]) OVER (
    PARTITION BY expr,...
    ORDER BY expr [ASC|DESC],...
)

 LAG()함수는  파티션 또는 결과 집합 내의 행 수만큼 현재 행 앞에 있는 expression행의 값을 반환합니다.

 

예시) orders, orderDetails, and productLines tables 

WITH productline_sales AS (
    SELECT productline,
           YEAR(orderDate) order_year,
           ROUND(SUM(quantityOrdered * priceEach),0) order_value
    FROM orders
    INNER JOIN orderdetails USING (orderNumber)
    INNER JOIN products USING (productCode)
    GROUP BY productline, order_year
)
SELECT
    productline, 
    order_year, 
    order_value,
    LAG(order_value, 1) OVER (
        PARTITION BY productLine
        ORDER BY order_year
    ) prev_year_order_value
FROM 
    productline_sales;

https://www.mysqltutorial.org/mysql-window-functions/mysql-lag-function/

Comments