Skip to content

SQL FIRST_VALUE() and LAST_VALUE()

FIRST_VALUE (), one of our new analytic functions that comes with SQL Server 2012, returns the first value in the sorted data set. LAST_VALUE () returns the last value in the sorted data set.

SELECT  cus.customer_id,cus.first_name, cus.last_name, 
	FIRST_VALUE(customer_id) OVER (PARTITION BY cus.first_name ORDER BY cus.first_name) 
	as  [first value]
FROM BikeStores.sales.customers as cus

SELECT  cus.customer_id,cus.first_name, cus.last_name, 
	LAST_VALUE(customer_id) OVER (PARTITION BY cus.first_name ORDER BY cus.first_name)
	as [last value]
FROM BikeStores.sales.customers as cus
SQL FIRST_VALUE() and LAST_VALUE()

SELECT  cus.customer_id,cus.first_name, cus.last_name, 
	FIRST_VALUE(customer_id) OVER (PARTITION BY cus.first_name ORDER BY cus.first_name) 
	as  [first value],
	LAST_VALUE(customer_id) OVER (PARTITION BY cus.first_name ORDER BY cus.first_name)
	as [last value]
FROM BikeStores.sales.customers as cus

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: