-- MOPDB
DELETE FROM CT_MRDS.A_TASK_HISTORY t WHERE EXISTS (
  SELECT 1
  FROM CT_MOPDB.A_LOAD_SUBPROCESS r
  WHERE 
      r.SUBPROCESS_NAME IN (
      SELECT DISTINCT SUBPROCESS_NAME 
      FROM CT_MOPDB.A_LOAD_HISTORY A
      LEFT JOIN CT_MOPDB.A_LOAD_SUBPROCESS B
      ON A.A_MOPDB_LOAD_SET_KEY = b.A_MOPDB_LOAD_SET_FK
      WHERE 
          WORKFLOW_NAME IN (
          'w_MOPDB_LM_ADHOC_ADJUSTMENT',
          'w_MOPDB_LM_BALANCESHEET',
          'w_MOPDB_LM_CSM_ADJUSTMENT',
          'w_MOPDB_LM_STANDING_FACILITY',
          'w_MOPDB_LM_CURRENT_ACCOUNTS',
          'w_MOPDB_LM_FORECAST',
          'w_MOPDB_LM_QRE_ADJUSTMENT',
          'w_MOPDB_LM_TTS'
      )
  )
	AND t.A_TASK_HISTORY_KEY      = r.A_LOAD_SUBPROCESS_KEY
	AND t.A_WORKFLOW_HISTORY_KEY  = r.A_MOPDB_LOAD_SET_FK
	AND NVL(t.TASK_RUN_ID,' ')    = NVL(CAST(NULL AS VARCHAR2(200)),' ')
	AND NVL(t.TASK_NAME,' ')      = NVL(CASE
                                        WHEN r.SUBPROCESS_NAME    = 'm_MOPDB_LM_T_STANDING_FACILITIES_OU_LM_STANDING_FACILITY_LOAD' THEN 'm_MOPDB_LM_T_STANDING_FACILITIES_OU_LM_STANDING_FACILITIES_LOAD'
                                        ELSE r.SUBPROCESS_NAME
                                      END,' ') 
	AND NVL(t.TASK_START,SYSDATE) = NVL(r.PROCESS_START,SYSDATE)
	AND NVL(t.TASK_END,SYSDATE)   = NVL(r.PROCESS_END,SYSDATE)
	AND NVL(t.TASK_SUCCESSFUL,' ')= NVL(r.PROCESS_SUCCESSFUL,' ')
	AND t.SERVICE_NAME            = 'MOPDB' 
);

COMMIT;