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 comment

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

Create a website or blog at WordPress.com

Up ↑

Design a site like this with WordPress.com
Get started