...
/Answer: Using FIRST_VALUE(), LAST_VALUE(), and NTH_VALUE()
Answer: Using FIRST_VALUE(), LAST_VALUE(), and NTH_VALUE()
Find a detailed explanation of how to use FIRST_VALUE(), LAST_VALUE(), and NTH_VALUE() window functions in SQL.
We'll cover the following...
Solution
The solution is given below:
-- The query to select specific values using SQL functionsSELECT SalesID, Month, SalesAmount,FIRST_VALUE(SalesAmount) OVER ( ORDER BY SalesID) AS FirstMonthSales,LAST_VALUE(SalesAmount) OVER ( ORDER BY SalesIDROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS LastMonthSales,NTH_VALUE(SalesAmount, 6) OVER ( ORDER BY SalesIDROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS JuneSalesFROM Sales;
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 AND UNBOUNDED FOLLOWING.Line 9: The
FROMclause specifies the table name asSales. ...