select
obj_address as OBJ_ADDRESS,
O.OBJ_CLASS as OBJ_CLASS,
O.OBJ_CLASS_ORG as OBJ_CLASS_ORG,
obj_code as OBJ_CODE,
obj_desc as OBJ_DESC,
o.obj_mrc as OBJ_MRC,
O.OBJ_OBTYPE as OBJ_OBTYPE,
O.OBJ_OBRTYPE as OBJ_OBRTYPE,
o.obj_org as OBJ_ORG,
o.obj_status as OBJ_STATUS,
( SELECT UCO_DESC
FROM r5ucodes
WHERE uco_rentity = 'OBST'
AND
UCO_CODE = OBJ_STATUS
)  as OBJ_STATUS_DESC,
obj_store as OBJ_STORE,
obj_syslevel as OBJ_SYSLEVEL,
obj_value as OBJ_VALUE,
obj_xcoordinate as OBJ_XCOORDINATE,
obj_ycoordinate as OBJ_YCOORDINATE,
(SELECT COUNT(*) FROM r5events e WHERE evt_rstatus IN ( 'Q', 'R' )
AND
evt_rtype IN ( 'JOB', 'PPM' )
AND
EXISTS (
SELECT 1
FROM r5ucodes
WHERE uco_rentity = 'JBTP'
AND
uco_code = evt_jobtype
AND
uco_rcode IN ( '*', 'BR', 'ST', 'PM', 'CAL', 'RP' )
)
AND
(  (<parameter.deptsec>  = 'OFF' )
OR
EXISTS (
SELECT 1
FROM r5departmentsecurity
WHERE dse_user = <parameter.r5user>
AND
dse_mrc = evt_mrc
)
)
AND evt_rstatus = 'R'
AND evt_object = obj_code
AND evt_object_org = obj_org) AS WOS
FROM  R5OBJECTS o
WHERE
obj_rstatus not in ('A', 'D')
AND obj_obrtype in ('A','S','P','L')
AND obj_notused = '-'
AND
((<parameter.deptsec>  = 'OFF' )
OR
EXISTS(
SELECT 1
FROM r5departmentsecurity
WHERE dse_user = <parameter.r5user>
AND
dse_mrc = obj_mrc
)
)
ORDER BY WOS DESC,
<parameter.fieldname> <parameter.sortorder>
