SELECT
OBJ_ADDRESS AS EVT_ADDRESS,
OBJ_XCOORDINATE AS EVT_XCOORDINATE,
OBJ_YCOORDINATE AS EVT_YCOORDINATE,
EVT_CODE AS EVT_CODE,
evt_desc  AS EVT_DESC,
EVT_JOBTYPE AS EVT_JOBTYPE,
(
SELECT UCO_DESC
FROM r5ucodes
WHERE uco_rentity = 'JBTP'
AND
UCO_CODE = EVT_JOBTYPE
)
AS EVT_JOBTYPE_DESC,
(
SELECT UCO_DESC
FROM r5ucodes
WHERE uco_rentity = 'JBPR'
AND
UCO_CODE = EVT_PRIORITY
)
AS EVT_PRIORITY_DESC,
(
SELECT MIN(CAST(diw_sequence AS integer)) AS minseq FROM r5dispatchevents, r5activities WHERE diw_event = evt_code AND diw_event=act_event AND diw_act=act_act AND act_completed ='-' AND diw_complete='-' AND NOT EXISTS (SELECT 1 FROM r5organizationoptions WHERE opa_code ='ACTDISCP' AND ','|| opa_desc ||',' LIKE ','||act_assignmentstatus||',%')
)
AS DIW_SEQUENCE,
EVT_MRC AS EVT_MRC,
EVT_OBJECT AS EVT_OBJECT,
OBJ_DESC AS EVT_OBJECT_DESC,
EVT_OBJECT_ORG AS EVT_OBJECT_ORG,
evt_obtype AS EVT_OBTYPE,
EVT_ORG AS EVT_ORG,
EVT_PPM AS EVT_PPM,
EVT_DUE AS EVT_DUE,
EVT_PRIORITY AS EVT_PRIORITY,
EVT_RSTATUS AS EVT_RSTATUS,
EVT_SAFETY AS EVT_SAFETY,
EVT_TOPOINT AS EVT_TOPOINT,
EVT_FROMPOINT AS EVT_FROMPOINT,
EVT_STATUS AS EVT_STATUS,
(
SELECT UCO_DESC
FROM r5ucodes
WHERE uco_rentity = 'EVST'
AND
UCO_CODE = EVT_STATUS
)
AS EVT_STATUS_DESC,
EVT_CLASS AS EVT_CLASS,
EVT_CLASS_ORG AS EVT_CLASS_ORG,
EVT_WARRANTY AS EVT_WARRANTY,
EVT_PERSON AS EVT_PERSON,
OBJ_GISOBJID as EVT_OBJECT_GISOBJID,
EVT_PPOINCLUDENONCONFORMITIES AS EVT_PPOINCLUDENONCONFORMITIES,
(CASE WHEN EXISTS(SELECT 1 FROM R5NONCONFORMOBSERVATIONS WHERE NCO_WORKORDER = EVT_CODE) THEN 1 ELSE 0 END) AS HASCONFORMITYRECORDS

FROM r5events e
LEFT OUTER JOIN r5objects ON OBJ_CODE = EVT_OBJECT AND OBJ_ORG = EVT_OBJECT_ORG
WHERE evt_rstatus IN ( 'Q', 'R' )
AND OBJ_GISOBJID is not null
AND
evt_org = <parameter.org>
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        (  EXISTS
(  SELECT 1              FROM r5personnel
WHERE per_user = <parameter.r5user>
AND evt_person = per_code           )
OR EXISTS
(  SELECT 1
FROM r5actschedules, r5personnel
WHERE acs_event = evt_code
AND per_user = <parameter.r5user>
AND acs_responsible = per_code           )        )

ORDER BY CASE
WHEN e.DMLTYPE='A' THEN 0
ELSE 1
END,
<parameter.fieldname> <parameter.sortorder>






