EDIT . In response to your comment, SQL Server supports window functions. One way to find the first and last bal values ββfor Session ID :
select distinct [Session ID] , first_value(bal) over (partition by [Session ID] order by id) as [start] , first_value(bal) over (partition by [Session ID] order by id desc) as [end] from Table1
Example in SQL Fiddle.
Another way (there are many) is to increase and decrease line numbers:
select [Session ID] , max(case when rn1 = 1 then bal end) as [start] , max(case when rn2 = 1 then bal end) as [end] from ( select row_number() over (partition by [Session ID] order by id) as rn1 , row_number() over (partition by [Session ID] order by id desc) as rn2 , * from Table1 ) as SubQueryAlias group by [Session ID]
Example in SQL Fiddle.
source share