Version for Oracle:
with jobList (jobid, steps) as ( select jobid, listagg(Status, ' ') WITHIN GROUP (ORDER BY id) from job_status group by jobid ) select 'FINISHED:' as Status , listagg(jobid, ' ') WITHIN GROUP (ORDER BY jobid) from jobList where instr(steps, 'Finished') > 0 union all select 'CANCELED:' as Status , listagg(jobid, ' ') WITHIN GROUP (ORDER BY jobid) from jobList where instr(steps, 'Finished') = 0 and instr(steps, 'Canceled') > 0 union all select 'FAILED:' as Status , listagg(jobid, ' ') WITHIN GROUP (ORDER BY jobid) from jobList where instr(steps, 'Failed') > 0 and instr(steps, 'Canceled') = 0 and instr(steps, 'Finished') = 0 union all select 'Active:' as Status , listagg(jobid, ' ') WITHIN GROUP (ORDER BY jobid) from jobList where instr(steps, 'Started') > 0 and instr(steps, 'Failed') = 0 and instr(steps, 'Canceled') = 0 and instr(steps, 'Finished') = 0
Basically, I put all the statuses for each jobid on a single line called steps . After that, I look for a string if a certain status exists or not. Since there can be more than one jobid for such criteria, I use listagg again to change the result to a string. If you have 2 finished tasks (with identifiers 1 and 5), you will see FINISHED: 1 5
Version for MySql with sample SQL Fiddle . This is a little longer since we do not have WITH on MySql.
select 'FINISHED:' as Status , group_concat( a.jobid separator ' ') as jobList from ( select jobid, group_concat(Status separator ' ') steps from job_status group by jobid ) a where instr(steps, 'Finished') > 0 union all select 'CANCELED:' as Status , group_concat( a.jobid separator ' ') as jobList from ( select jobid, group_concat(Status separator ' ') steps from job_status group by jobid ) a where instr(steps, 'Finished') = 0 and instr(steps, 'Canceled') > 0 union all select 'FAILED:' as Status , group_concat( a.jobid separator ' ') as jobList from ( select jobid, group_concat(Status separator ' ') steps from job_status group by jobid ) a where instr(steps, 'Failed') > 0 and instr(steps, 'Canceled') = 0 and instr(steps, 'Finished') = 0 union all select 'Active:' as Status , group_concat( a.jobid separator ' ') as jobList from ( select jobid, group_concat(Status separator ' ') steps from job_status group by jobid ) a where instr(steps, 'Started') > 0 and instr(steps, 'Failed') = 0 and instr(steps, 'Canceled') = 0 and instr(steps, 'Finished') = 0