We have mentioned the LEAD and LAG functions announced with SQL Server 2012. In this article, we will examine the FIRST_VALUE function.
Now let’s look at the basic template:
FIRST_VALUE ( [scalar_expression )
OVER ( [ partition_by_clause ] order_by_clause [ rows_range_clause ] )
The FIRST_VALUE function takes a value as a parameter. This value can be either a column or an expression. Order By and Partition By on the OVER Clause affects the value to be obtained.
In our examples, we used the AdventureWorks database that was create for SQL Server 2008R2.
When we run the below query, we will successfully obtain the first order date of the customer, whose CustomerID is 29994.
FIRST_VALUE(OrderDate) OVER (ORDER BY OrderDate) as FirstOrderDate
When we examine the query and the result, we group by year with PARTITION BY in the OVER Clause. Then we get the first order date for each year using the FIRST VALUE function.
In this example, there are two more points to consider:
- Partition By statement uses the YEAR function
- The value given to the First_Value function is obtained from the CONVERT function.
OVER (Partition BY Year(OrderDate) ORDER BY OrderDate) AS FirstOrderDate