Answer: Using LAG() And LEAD()
Find a detailed explanation of using LAG() and LEAD() functions.
Solution
The solution is given below:
-- The query to use LAG() and LEAD() functionsSELECT SalesID, Month, SalesAmount,LAG(SalesAmount, 1) OVER (ORDER BY MONTHNAME(Month)) AS PreviousMonthSales,LEAD(SalesAmount, 1) OVER (ORDER BY MONTHNAME(Month)) AS NextMonthSalesFROM SalesWHERE CategoryID = 1ORDER BY MONTHNAME(MONTH) DESC, SalesID ASC;
Code explanation
The explanation of the solution code is given below:
Lines 2–4: The
SELECT
statement selects the columnsSalesID
,Month
, andSalesAmount
. TheLAG()
function gets the sales from the previous month and labels it asPreviousMonthSales
and theLEAD()
function gets the sales from the next month and labels it asNextMonthSales
.Line 5: The
FROM
clause specifies the table name asSales
.Line 6: The
WHERE
clause specifies the condition on which we filter the results to include only records withCategoryID
equal to 1.Line 7: The
ORDER BY
clause sorts the results by theMONTH
column in descending order and theSalesID
column in ascending order.
Recalling relevant concepts
We have covered the following concepts in this question:
Selective columns
Aliases ...