


CREATE OR REPLACE FUNCTION mostValuableClerk(months IN NUMBER) RETURN NUMBER
IS
    startMonat DATE;
    finalclerkid NUMBER;
    maxanzahlcleanings NUMBER;
BEGIN
    startMonat := ADD_MONTHS(SYSDATE,-months);

    SELECT CLERKID, MAX(Anzahl) INTO finalclerkid, maxanzahlcleanings FROM
    (
    SELECT DISTINCT CLERKID, COUNT(CLERKID) AS Anzahl
        From
        (
        SELECT clcl.CLERKID
         FROM CLEANINGCLERK clcl
         INNER JOIN CLEANINGPLAN clpl ON clcl.CLEANINGPLANID = clpl.CLEANINGPLANID
         WHERE clpl."date" >= startMonat
         )
    GROUP BY CLERKID
    )
    GROUP BY CLERKID;

    return finalclerkid;
END;