Tuesday, December 2, 2014

First and Last value in SQL Server 2012

Sql server 2012 provides new analytical functions FIRST_VALUE and LAST_VALUE. 
 First_Value: Returns the first value in an ordered set of value
LAST_VALUE: Returns the last value in an ordered set of values
So here is example how to use these function in select query .in this query    return first row and the last row for all records in a result set.

Suppose we have employee table it has following columns
ENO
ENAME
DEPTID
JOBTYPE
SALARY





101
Anil
10
Assistant
10000
102
Sunny
20
Analyst
50000
103
Karan
20
Clerk
12000
104
Sam
30
Assistant
20000
105
Peter
30
Manager
60000
106
Lucky
30
Sr analyst
55000
107
Sandy
40
Team Lead
44000

select ENO, ENAME,DEPTID,JOBTYPE,FIRST_VALUE(ENO) OVER (ORDER BY ENO) FIrstValue,
LAST_VALUE(ENO) OVER (ORDER BY ENO) Lastvalue from emp
When u run this query you find   thw ouput
ENO
ENAME
DEPTID
JOBTYPE
FIRSTVALUE
LASTVALUE
101
Anil
10
Assistant
101
101
102
Sunny
20
Analyst
101
102
103
Karan
20
Clerk
101
103
104
Sam
30
Assistant
101
104
105
Peter
30
Manager
101
105
106
Lucky
30
Sr analyst
101
106
107
Sandy
40
Team Lead
101
107

Here is frist value same all records and last value change each records

No comments:

Post a Comment

http://blogsiteslist.com