Answer: Using LAG() And LEAD()
Explore how to apply SQL LAG and LEAD window functions to retrieve previous and next row values in a dataset. Understand their syntax and usage in SELECT statements with filtering and ordering. Gain insight into alternate methods such as CTEs, LEFT JOINs, and subqueries for similar results. This lesson helps you write and interpret queries for comparing sales data across periods, enhancing your analytical SQL skills.
Solution
The solution is given below:
Code explanation
The explanation of the solution code is given below:
Lines 2–4: The
SELECTstatement selects the columnsSalesID,Month, andSalesAmount. TheLAG()function gets the sales from the previous month and labels it asPreviousMonthSalesand theLEAD()function gets the sales from the next month and labels it asNextMonthSales.Line 5: The
FROMclause specifies the table name asSales.Line 6: The
WHEREclause specifies the condition on which we filter the results to include only records withCategoryIDequal to 1.Line 7: The
ORDER BYclause sorts the results by theMONTHcolumn in descending order and theSalesIDcolumn in ascending order.
Recalling relevant concepts
We have covered the ...