SELECT
NCO_PK as nonconformitypk,
NCO_CODE as nonconformity,
NCO_OBSERVATION as observation,
NCF_CODE as nonconformitycode,
NCF_DESC as description,
NCF_ORG as organization,
NCF_OBJECT as equipment,
OBJ_DESC as equipmentdesc,
NCF_OBJECT_ORG as equipmentorg,
NCO_RECORDED as daterecorded,
NCO_RECORDEDBY as recordedby,
NCO_UPDATED as updated,
NCO_SEVERITY as severity,
(
SELECT UCO_DESC FROM r5ucodes WHERE uco_rentity = 'SEVE' AND UCO_CODE = NCO_SEVERITY
) AS severity_display,
NCO_STATUS as status,
(
SELECT UCO_DESC FROM r5ucodes WHERE uco_rentity = 'NOST' AND UCO_CODE = NCO_STATUS
)
AS status_display,
CASE ( SELECT COUNT(*) FROM r5addetails WHERE add_rentity = 'NOCO' AND add_code = nco_pk) WHEN 0 THEN '-' ELSE '+' END as observation_comments,
CASE ( SELECT COUNT(*) FROM r5documents WHERE doc_rentity = 'NOCO' AND doc_entitycode = nco_pk) WHEN 0 THEN '-' ELSE '+' END as observation_documents,
(
SELECT NCP_USEOBSSTATUS FROM r5nonconformitysetup WHERE NCP_ORG = <param.organization>
) AS NCP_USEOBSSTATUS

FROM r5nonconformobservations INNER JOIN r5nonconformities ON (ncf_code = nco_code)
LEFT OUTER JOIN r5objects ON (obj_code = ncf_object AND obj_org = ncf_object_org)
WHERE ncf_code = <param.nonconformity> AND ncf_org = <param.organization> AND (<parameter.deptsec> ='OFF' OR 
(EXISTS( SELECT dse_mrc FROM r5departmentsecurity WHERE dse_user =<parameter.r5user> AND dse_mrc = ncf_mrc)))
ORDER BY COALESCE([nco_recorded],[nco_updated],[nco_created]) DESC
