I have a table similar to this CancelLog
|ID| membrecia| User | DateCancel | Motivo |
| 2| 1 | uS1 | 7/29/2011 | ... |
| 3| 1 | uS2 | 7/30/2011 | ... |
| 6| 1 | uS1 | 8/02/2011 | ... |
| 1| 2 | uS1 | 7/28/2011 | ... |
| 4| 2 | uS2 | 7/30/2011 | .... |
| 5| 2 | uS3 | 8/01/2011 | . |
| 6| 3 | uS1 | 8/02/2011 | . |
and I would like to get The most recent record of each membership is to say something like this
|ID| membrecia| User | DateCancel | Motivo |
| 6| 1 | uS1 | 8/02/2011 | ... |
| 5| 2 | uS3 | 8/01/2011 | . |
| 6| 3 | uS1 | 8/02/2011 | . |
I was doing something similar to this,
select l.membrecia, l.[USER] , l.DateCancel, count(*), max(l.DateCancel)
from CancelLog l
group by l.membrecia, l.[USER], l.DateCancel;
count(*) y max(l.DateCancel)
I only use them for information, they will not be in the final query
if it gives me the most recent results, but if a membership is "cancelled"* by several different users, it brings me the data of all users who canceled it
|ID| membrecia| User | DateCancel | Motivo |
| 3| 1 | uS2 | 7/30/2011 | ... |
| 6| 1 | uS1 | 8/02/2011 | ... |
| 1| 2 | uS1 | 7/28/2011 | ... |
| 4| 2 | uS2 | 7/30/2011 | .... |
| 5| 2 | uS3 | 8/01/2011 | . |
I would like to get the records like the ones shown in table 2.
*During cancellation, the "Reason" can be changed, and due to this change a new record is created in the log.
change from motivo
"Temporary removal" to "Definitive removal", so I am only interested in the last change regardless of the user, but I do need the last user who made the change in the results.
Does anyone know how I could get those logs?
What you are looking for is achieved very easily using the window function
row_number()
. There is no need to use temporary tables and loops, which is too complicated and expensive for this type of query:Dear, I did an exercise to be able to obtain the data that you request in the way that you request it, I enclose a query of how I did it, perhaps it can be of use to you. Greetings.
Here the Query.
Thanks to those who helped, but I managed to solve it as follows
As you can see I made a subQuery, which I get the most recent id of a given membership, ordering it from highest to lowest, getting this highest id, I compare it with the main query id and I got the desired result