Friday , April 19 2024

FIRST_VALUE Function in SQL Server(TSQL)

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:

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.

Example 1:

When we run the below query, we will successfully obtain the first order date of the customer, whose CustomerID is 29994.

Example 2:

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.

 

Loading

About Resul ÇAVUŞOĞLU

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories