Answer: Using FIRST_VALUE(), LAST_VALUE(), and NTH_VALUE()
Explore how to apply the SQL window functions FIRST_VALUE LAST_VALUE and NTH_VALUE to retrieve specific records from ordered sales data. Learn to write queries that rank and analyze sales performance using these functions and understand their syntax, usage, and alternatives. This lesson helps you master practical skills for intermediate SQL interviews.
We'll cover the following...
Solution
The solution is given below:
Code explanation
The explanation of the solution code is given below:
Line 2: The
SELECTstatement selects the columnsSalesID,Month, andSalesAmount. We useASto set an alias for each calculated column.Lines 3–4: The
FIRST_VALUE()function gets the sales from the first recordedSalesAmountbased on the order ofSalesID.Lines 5–6: The
LAST_VALUE()function gets the sales from the last recordedSalesAmountbased on the order ofSalesID. It considers the entire dataset with theROWSclause set toUNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.Lines 7–8: The
NTH_VALUE()function retrieves the sales from the 6th recordedSalesAmountbased on the order ofSalesID. It considers the entire dataset with theROWSclause set toUNBOUNDED PRECEDING...