SQL select first (or last) row of a group
My goal is to select the amendment id of the most recently amended gift.
The most recently amended gift will have the highest sequence number.
giftamendment table
giftid | sequence | amendmentid |
---|---|---|
249138 | 2 | 6517441 |
249138 | 1 | 6078366 |
249139 | 1 | 6078814 |
249246 | 3 | 13162954 |
249246 | 2 | 12731461 |
249246 | 1 | 12406299 |
sql over clause
https://msdn.microsoft.com/en-us/library/ms189461.aspx
In laymans terms, the over clause makes the row I want have a value of 1 for
the uno
field.
select
giftid,
sequence,
amendmentid,
row_number()
over(partition by giftid order by sequence desc) uno
from giftamendment
query results
giftid | sequence | amendmentid | uno |
---|---|---|---|
249138 | 2 | 6517441 | 1 |
249138 | 1 | 6078366 | 2 |
249139 | 1 | 6078814 | 1 |
249246 | 3 | 13162954 | 1 |
249246 | 2 | 12731461 | 2 |
249246 | 1 | 12406299 | 3 |
Final Solution
Finally I just select the rows from summary where uno is 1.
with summary as (
select
giftid,
sequence,
amendmentid,
row_number()
over(partition by giftid order by sequence desc) uno
from giftamendment
)
select amendmentid from summary where uno = 1
query results
amendmentid |
---|
6517441 |
6078814 |
13162954 |