/ Published in: MySQL
Created as reply to question on ittoolbox.com:"Need your help in writing a query to pull audit history i.e. Last updated by a user 'XYZ' and for the same record key (ID) the second last record in the audit history table. i.e. Last update by this user and the previous updated record to this record by anybody e.g. "
http://database.ittoolbox.com/groups/technical-functional/sql-l/sql-to-find-records-updated-by-particular-user-and-the-prior-one-5732386
This snippet is written to show a step-by-step process of building the query to produce the results. It started with the simple query, then builds on that to the final query and results.
http://database.ittoolbox.com/groups/technical-functional/sql-l/sql-to-find-records-updated-by-particular-user-and-the-prior-one-5732386
This snippet is written to show a step-by-step process of building the query to produce the results. It started with the simple query, then builds on that to the final query and results.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
-- Let's restate the problem and solve it in pieces. Then put the pieces together. -- CREATE THE DATA id int, update_date date ); -- WHAT'S IN THE TABLE? -- (1) WHEN WAS EACH ROW MOST RECENTLY UPDATED? from theTable group by id; -- (2) WHO MADE THAT UPDATE? from theTable from theTable group by id ); -- (3) WHEN WERE ALL THE PREVIOUS UPDATES FOR THAT ROW? select secondUpdate.id, secondUpdate.update_date from theTable secondUpdate join ( from theTable group by id ) lastUpdate on secondUpdate.id = lastUpdate.id and secondUpdate.update_date < lastUpdate.max_update_date ; -- (4) WHAT'S THE MOST RECENT OF THOSE PREVIOUS UPDATES? from theTable secondUpdate join ( from theTable group by id ) lastUpdate on secondUpdate.id = lastUpdate.id and secondUpdate.update_date < lastUpdate.max_update_date group by secondUpdate.id; -- (5) WHO MADE THAT LAST PREVIOUS UPDATE? from theTable T join ( from theTable secondUpdate join ( from theTable group by id ) lastUpdate on secondUpdate.id = lastUpdate.id and secondUpdate.update_date < lastUpdate.max_update_date group by secondUpdate.id ) lastPreviousUpdate on T.id = lastPreviousUpdate.id and T.update_date = lastPreviousUpdate.max_previous_date ; -- (6) NOW GET BOTH OF THEM select L.id "Record", L.updated_by "lastUpdater", L.update_date "lastUpdate", P.updated_by "prevUpdater", P.update_date "prevUpdate" ( from theTable from theTable group by id ) ) L ( from theTable T join ( from theTable secondUpdate join ( from theTable group by id ) lastUpdate on secondUpdate.id = lastUpdate.id and secondUpdate.update_date < lastUpdate.max_update_date group by secondUpdate.id ) lastPreviousUpdate on T.id = lastPreviousUpdate.id and T.update_date = lastPreviousUpdate.max_previous_date ) P on L.id = P.id order by L.id ;