CREATE OR REPLACE TABLE lifecycle_times ( id int primary key auto_increment, project_number varchar(25), ready_for_review datetime, ready_for_review_two datetime, ready_for_deliver datetime, sealed datetime, delivered datetime, has_been_invoiced datetime, ready_to_invoice datetime ); CREATE OR REPLACE INDEX lifetimes_refnum on project_lifecycle (project_number); INSERT INTO lifecycle_times (project_number) SELECT DISTINCT project_number FROM project_lifecycle; UPDATE lifecycle_times set ready_for_review = (SELECT timestamp from project_lifecycle where new_value = '+READY_FOR_REVIEW' and project_lifecycle.project_number = lifecycle_times.project_number order by timestamp desc limit 1), ready_for_review_two = (SELECT timestamp from project_lifecycle where new_value = '+READY_FOR_REVIEW2' and project_lifecycle.project_number = lifecycle_times.project_number order by timestamp desc limit 1), ready_for_deliver = (SELECT timestamp from project_lifecycle where new_value = '+READY_FOR_DELIVER' and project_lifecycle.project_number = lifecycle_times.project_number order by timestamp desc limit 1), ready_for_deliver = (SELECT timestamp from project_lifecycle where new_value = '+READY_FOR_DELIVER' and project_lifecycle.project_number = lifecycle_times.project_number order by timestamp desc limit 1), sealed = (SELECT timestamp from project_lifecycle where new_value = '+SEALED' and project_lifecycle.project_number = lifecycle_times.project_number order by timestamp desc limit 1), delivered = (SELECT timestamp from project_lifecycle where new_value = '+DELIVERED' and project_lifecycle.project_number = lifecycle_times.project_number order by timestamp desc limit 1), has_been_invoiced = (SELECT timestamp from project_lifecycle where new_value = '+HAS_BEEN_INVOICED' and project_lifecycle.project_number = lifecycle_times.project_number order by timestamp desc limit 1), ready_to_invoice = (SELECT timestamp from project_lifecycle where new_value = '+READY_TO_INVOICE' and project_lifecycle.project_number = lifecycle_times.project_number order by timestamp desc limit 1) ;