CREATE OR REPLACE FUNCTION MEDCUSTO_SUBGRU_COC(
  P_CDFILIAL         IN VARCHAR2,
  P_CDCIA            IN VARCHAR2,
  P_CDMANCIA         IN VARCHAR2,
  P_NRSERVICOCIAFILI IN NUMBER,
  P_CDCLASSE         IN VARCHAR2,
  P_CDSUBGRU         IN VARCHAR2,
  P_NRSEQSUBGRUSEMAM IN NUMBER,
  P_NRORG            IN NUMBER,
  P_DATACUSTO        IN VARCHAR2,
  P_TIPOCUSTO        IN VARCHAR2)
RETURN FLOAT
AS
  V_MEDCUS FLOAT;
BEGIN
  SELECT AVG(CUSTO_SUBGRU_COC(CSM.CDFILIAL, CSM.CDCIA, CSM.CDMANCIA, CSM.NRSERVICOCIAFILI, CSM.CDCLASSE, CSM.CDSUBGRU, CSM.NRSEQSUBGRUSEMAM, CSM.CDCICLO, CSM.NRORG, P_DATACUSTO, P_TIPOCUSTO))
  INTO V_MEDCUS
  FROM CICLOSUBGRUSEMAM CSM
  WHERE CSM.CDFILIAL       = P_CDFILIAL
  AND CSM.CDCIA            = P_CDCIA
  AND CSM.CDMANCIA         = P_CDMANCIA
  AND CSM.NRSERVICOCIAFILI = P_NRSERVICOCIAFILI
  AND CSM.CDCLASSE         = P_CDCLASSE
  AND CSM.CDSUBGRU         = P_CDSUBGRU
  AND CSM.NRSEQSUBGRUSEMAM = P_NRSEQSUBGRUSEMAM
  AND CSM.NRORG            = P_NRORG;

  V_MEDCUS := NVL(V_MEDCUS, 0);
  V_MEDCUS := CASE WHEN V_MEDCUS > 0 AND
                        ROUND(V_MEDCUS, 2) = 0.00 THEN 0.01
                   ELSE ROUND(V_MEDCUS, 2)
              END;

  RETURN NVL(V_MEDCUS, 0);
END;
/