SELECT * FROM (
SELECT DISTINCT(cast(m.mlp_line as varchar(30))) AS matlist_lineno,
       p.PAR_CODE AS partcode,
       p.PAR_DESC AS partdescription,
       p.PAR_UOM AS uom,
       cast(a.ACT_ACT as varchar(30)) AS activity,
       null  AS storecode,
       p.PAR_ORG AS partorganization,
       cast(m.MLP_QTY as varchar(30)) AS plannedqty,
       null AS usedqty,
       m.MLP_OPTIONAL AS matoptional
  FROM R5MATLPARTS m, R5EVENTS e
       INNER JOIN R5Parts p
               ON (  ( m.mlp_part = p.PAR_CODE ) 
    AND
( m.mlp_part_org = p.PAR_ORG )  ) 
       INNER JOIN R5ACTIVITIES a
               ON ( a.ACT_MATLIST = m.MLP_MATLIST ) 
 WHERE ( a.ACT_EVENT = <param.workordernum>
           OR
           a.ACT_EVENT IN ( 
               SELECT EVT_CODE
                 FROM R5EVENTS
                WHERE EVT_JOBTYPE = 'MEC' 
                      AND
                      EVT_PARENT = <param.workordernum>
                      AND
                      EVT_ORG = <param.organization>
           ) 
        )
AND e.evt_code = a.act_event
AND    ((COALESCE( e.evt_object, 'x' ) = COALESCE( m.mlp_code, e.evt_object, 'x' ))
AND    (COALESCE( e.evt_object_org, 'x' )  = COALESCE( m.mlp_code_org, e.evt_object_org, 'x' ))
OR (     m.mlp_obrtype = 'C'
AND EXISTS ( SELECT obj_code
FROM   r5objects
WHERE  obj_code     = e.evt_object
AND    obj_org      = e.evt_object_org
AND    obj_category = m.mlp_code ) ) )
UNION ALL
SELECT '0' AS matlist_lineno,
       TRL_PART AS partcode,
       PAR_DESC AS partdescription,
       PAR_UOM AS uom,
       cast(TRL_ACT as varchar(30)) AS activity,
       TRL_STORE AS storecode,
       TRL_PART_ORG AS partorganization,
       0 AS plannedqty,
       SUM( TRL_QTY) AS usedqty,
       '-' AS matoptional
  FROM R5TRANSLINES
       INNER JOIN R5PARTS
               ON (TRL_PART = PAR_CODE AND TRL_PART_ORG = PAR_ORG)
       INNER JOIN R5EVENTS
               ON TRL_EVENT = EVT_CODE
WHERE ( TRL_EVENT = <param.workordernum>
           OR
           TRL_EVENT IN ( 
               SELECT EVT_CODE
                 FROM R5EVENTS
                WHERE EVT_JOBTYPE = 'MEC' 
                      AND
                      EVT_PARENT = <param.workordernum>
           ) 
           
           AND
       EVT_ORG = <param.organization> ) 
       AND
       TRL_RTYPE = 'I' 
       AND
       TRL_QTY <> 0
GROUP BY TRL_PART,
          PAR_DESC,
          TRL_ACT,
          TRL_STORE,
          TRL_PART_ORG)
          WHERE 1=1

