Compare two records column by column in same table
Ben CMar 7 2012 — edited Mar 8 2012Hi All,
I have an address table with ID as the PK but there can be more than one ID. I need to take the latest address record and first see if that same ID has a previous address record and if so, compare each column to see if the data has changed. I only need to compare the latest record with the next latest record.
I cannot figure this out at all. I can of course use the MAX function to get the latest address records but do not know how I can pull the next latest address record that matches the ID and compare each column.
Sample table:
ID street city state zip effective_date
1 123 main chicago IL 60111 3-7-2012
2 34 N 13th new york NY 18374 3-7-2012
3 15 N main Dallas TX 47389 3-7-2012
1 89 N main chicago IL 60111 1-5-2012
1 16 East St columbus OH 47382 12-10-2011
2 34 N 13th new york NY 18374 10-7-2011
2 15 S Elm new york NY 18374 09-1-2011
3 15 N main Dallas TX 47389 10-4-2011
SO...in the table above using today as the latest record date, based of my criteria I would only want to pull record ID 1 and 2 since the next most recent record for those IDs have had at least one of their address data change. ID 3 has exactly the same address data so I would not consider that in my criteria.
Can i do this with SQL only or will i need to create a procedure or function?
Any help is appreciated
Ben