...
/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
SELECT
statement selects the columnsSalesID
,Month
, andSalesAmount
. We useAS
to set an alias for each calculated column.Lines 3–4: The
FIRST_VALUE()
function gets the sales from the first recordedSalesAmount
based on the order ofSalesID
.Lines 5–6: The
LAST_VALUE()
function gets the sales from the last recordedSalesAmount
based on the order ofSalesID
. It considers the entire dataset with theROWS
clause set toUNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
.Lines 7–8: The
NTH_VALUE()
function retrieves the sales from the 6th recordedSalesAmount
based on the order ofSalesID
. It considers the entire dataset with theROWS
clause set toUNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
.Line 9: The
FROM
clause specifies the table name asSales
. ...