Search code examples
sqlsql-serverskip

SQL Query to get the workorders which skipped some lines processing


As I am not expert in writing the SQL queries so want for help.

I have the below given dataset

I need to write a query to get all the workorderid's which have skipped the process and moved to next seq_no , ex:
workorderid = AW1 which has a line "open" for seq_no=30 and went ahead to "complete" for seq_no = 40

The final result set should look like below

Workorderid
----------- 
AW1  
AW3

enter image description here


Solution

  • One method simply uses conditional aggregation:

    select workorderid
    from t
    group by workorderid
    having (max(case when status = 'Open' then seq_no end) <
            max(case when status = 'Complete' then seq_no end)
           )
    

    That is, is there a 'Complete' after the last 'Open', based on seq_no.