As the title suggests, I'd like to select the first and last row of each set of rows grouped with a GROUP BY
.
I've this table with the following data:
id group val start end
1 10 36 465 89
2 10 35 55 11
3 10 34 20 456
4 20 38 1140 1177
5 20 22 566 788
6 20 1235 789 4796
7 20 7894 741 1067
What I need to get is the first value of the column start and last value of the column end with group by the group column.
The resultant table should be as below:
id group val start end
1 10 36 465 89
3 10 34 20 456
4 20 38 1140 1177
7 20 7894 741 1067
I did a query but with FIRST_VALUE
and LAST_VALUE
and over (partition by)
. It works in SQL Server 2012 but didn't work in SQL Server 2008. I need a query that can be executed in SQL Server 2008.
How to two query 'UNION'
How about using
ROW_NUMBER
:SQL Fiddle
This is one way -
Fiddle: http://sqlfiddle.com/#!3/c682f/1/0
Another approach: