LEAD & LAG Functions
Coddy SQL 여정의 기초 섹션에 포함된 레슨 — 72개 중 61번째.
LEAD와 LAG 함수는 현재 행의 값을 n 단계 뒤로 또는 n 단계 앞으로 접근할 수 있게 합니다.
예를 들어, 현재 행과 한 달 전의 회사 수익 비율을 계산하려면, 이전 달의 값을 추출할 수 있습니다:
| id | revenue | month |
| 1 | 532 | 5 |
| 2 | 492 | 6 |
| 3 | 393 | 7 |
| 4 | 723 | 8 |
SELECT id, revenue, LAG(revenue, 1) OVER (ORDER BY MONTH) as prev_month_revenue
FROM table1 ORDER BY id다음과 같은 표를 생성합니다:
| id | revenue | prev_month_revenue |
| 1 | 532 | |
| 2 | 492 | 532 |
| 3 | 393 | 492 |
| 4 | 723 | 393 |
이 방법으로 prev_month_revenue/revenue 비율을 계산할 수 있습니다.
대신 LEAD 함수를 사용하면 각 행의 다음 달 수익을 가져올 것입니다:
SELECT id, revenue, LEAD(revenue, 1) OVER (ORDER BY MONTH) as next_month_revenue
FROM table1 ORDER BY id| id | revenue | next_month_revenue |
| 1 | 532 | 492 |
| 2 | 492 | 393 |
| 3 | 393 | 723 |
| 4 | 723 |
챌린지
쉬움사용 가능한 테이블 및 열:
<strong>air_conditioners</strong>:<strong>id</strong>,<strong>efficiency</strong>,<strong>strength</strong>,<strong>month</strong>
각 에어컨의 효율성을 이전 것과 비교하세요.
id를 기준으로 설치된 이전 에어컨의 효율성과 함께 각 에어컨의 효율성을 보여주는 쿼리를 작성하세요. 또한, 현재와 이전 에어컨 간의 효율성 차이를 계산하세요. 결과를 <strong>id</strong>와 <strong>efficiency</strong>를 오름차순으로 정렬하세요.
예상 출력 열:
idefficiencyprevious_efficiency(LAG 사용)efficiency_difference(현재 효율성 - 이전 효율성)
이 쿼리 후에, previous_efficiency가 비어 있거나 efficiency_difference가 비어 있는 행을 다음과 같이 필터링하세요:
SELECT * FROM (
-- Your query here
)
WHERE previous_efficiency != 0치트 시트
LAG 및 LEAD 함수는 이전 또는 다음 행의 값에 액세스할 수 있게 합니다:
LAG 함수 - 이전 행의 값을 가져옵니다:
LAG(column_name, n) OVER (ORDER BY column)LEAD 함수 - 다음 행의 값을 가져옵니다:
LEAD(column_name, n) OVER (ORDER BY column)LAG를 사용하여 이전 달의 수익을 가져오는 예:
SELECT id, revenue, LAG(revenue, 1) OVER (ORDER BY month) as prev_month_revenue
FROM table1 ORDER BY idLEAD를 사용하여 다음 달의 수익을 가져오는 예:
SELECT id, revenue, LEAD(revenue, 1) OVER (ORDER BY MONTH) as next_month_revenue
FROM table1 ORDER BY id첫 번째 행은 LAG 값에 대해 NULL을 가지며, 마지막 행은 LEAD 값에 대해 NULL을 가집니다.
직접 해보기
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
기초의 모든 레슨
4More Keywords
The IN keywordThe BETWEEN keywordThe LIKE keywordThe AS keywordRecap - Cellphone Models2Conditions
Conditions BasicsThe AND keywordThe OR keywordThe NOT keywordMultiple Conditions CombinedParenthesisBooleans5Arithmetic Operations
Mathematical OperatorsMathematical ColumnsThe Modulo OperationThe ROUND() Function8Statistics
Built-In Aggregate Part 1Built-In Aggregate Part 2Grouping Part 1Grouping Part 2Subqueries Part 1Subqueries Part 2Recap - Total Gain ShopRecap - Scooter ShopRecap - Coffee Shop11Window Functions part 1
ROW_NUMBER functionORDER BY criterionPARTITION BY criterionPARTITION & ORDERLEAD & LAG FunctionsRecap - LEAD & LAGRecap - PicturesRecap - Boxes3Specific Return Format
Null valuesSort Results Part 1Sort Results Part 2Recap - Cyber Security FirmLimit number of recordsRecap - Vehicle Factory6Intro Challenges
Recap - Parliamentary ElectionRecap - Police Criminal ArrestRecap - Bar Beverage ContainerRecap - Engineer new columns