본문 바로가기
카테고리 없음

[Postgresql] LEAD() 다음행을 가져와주는 LEAD 함수

by 개탱 2023. 9. 6.
728x90

 

PostgreSQL에서 LEAD 함수는 데이터베이스 테이블의 행 간에 다음 행의 값을 가져오는 윈도우 함수 중 하나입니다. 이 함수는 데이터 분석과 보고서 작성에서 유용하게 사용됩니다.

LEAD 함수 기본 사용법

LEAD 함수의 기본 사용법은 다음과 같습니다:

SELECT
  column_name,
  LEAD(column_name, offset, default_value) OVER (PARTITION BY partition_column ORDER BY order_column) AS leaded_value
FROM
  table_name;
        

column_name은 현재 행의 값을 가져올 컬럼 이름을 나타내며, table_name은 데이터를 조회할 테이블 이름입니다. offset은 이전 행의 상대적인 위치를 나타내며, default_value는 이전 행이 없을 경우 사용할 기본값입니다.

 

expression

The expression is evaluated against the following row based on a specified offset from the current row. The expression can be a column, expression, subquery that must evaluate to a single value. And it cannot be a window function.

offset

The offset is a positive integer that specifies the number of rows forwarding from the current row from which to access data. The offset can be an expression, subquery, or column.

The offset defaults to 1 if you don’t specify it.

default_value

The default_value is the return value if the offset goes beyond the scope of the partition. The default_value defaults to NULL if you omit it.

 

 

예제 1: 다음 값 가져오기

아래 예제에서는 테이블 sales에서 각 월별 매출을 조회하고, 다음 월의 매출을 함께 표시합니다:

SELECT
  month,
  revenue,
  LEAD(revenue) OVER (ORDER BY month) AS next_month_revenue
FROM
  sales;
        

예제 2: 파티션을 기준으로 다음 값 가져오기

다음 예제에서는 테이블 orders에서 각 고객별 주문을 조회하고, 고객별로 주문된 상품의 다음 주문 수량을 함께 표시합니다:

SELECT
  customer_id,
  product_name,
  quantity,
  LEAD(quantity) OVER (PARTITION BY customer_id ORDER BY order_date) AS next_order_quantity
FROM
  orders;
        

예제 3: 직후 행의 값을 가져와서 더하기

다음 예제에서는 테이블 numbers에서 각 숫자를 조회하고, 직후 숫자의 값을 가져와 현재 숫자와 더합니다:

SELECT
  number,
  LEAD(number, 1, 0) OVER (ORDER BY id) + number AS sum_with_next
FROM
  numbers;
        

 

 

댓글