I have a table that tracks that date of various stages of completion for a set of equipment. I need to identify the most recently updated piece of equipment (i.e., the equipment with the most recent date stamp) regardless of which stage was updated and return the equipment id, the update date and the stage. Easy, right? Well, it's a bit trickier than it sounds. Here's the catch: each stage is represented as a different field in the table and redesigning the table structure isn't an option (a transactional table would make this a no brainer.) Here's what the table structure looks like.
equip_id (text)
stage_1_process (date)
stage_2_process (date)
stage_3_process (date)
stage_4_process (date)
stage_5_process (date)
If the field contains a date then the stage is considered complete; if the field is empty then the stage is considered unfinished.
A union query with a Max() function can get the most recent date:
SELECT Max(dt) AS latest
FROM (
SELECT Max(stage_1_process) AS dt, 'Stage 1' as stage
FROM equip_status
UNION
SELECT Max(stage_2_process) AS dt, 'Stage 2' as stage
FROM equip_status
UNION
SELECT Max(stage_3_process) AS dt, 'Stage 3' as stage
FROM equip_status
UNION
SELECT Max(stage_4_process) AS dt, 'Stage 4' as stage
FROM equip_status
UNION
SELECT Max(stage_5_process) AS dt, 'Stage 5' as stage
FROM equip_status) AS U;
The 'stage' alias is added to capture which stage that latest date is associate with. However, I don't know how to return it in the top-level query nor how to capture the equip_id, as it isn't derivable from an aggregate function.
Here's an example of the result set I need to return:
equip_id | stage | latest
--------------------------------------------
A12345 | Stage 3 | 4/21/2016 3:56:39 PM
Thanks for any help!