Delimiter //
Drop Procedure If Exists BUSINESS_PV_FI_KEY_GRAPH//
Create Procedure BUSINESS_PV_FI_KEY_GRAPH (
    In accoutId Int  Unsigned
    , In beginDate varchar(30)
    , In endDate varchar(30)
) 
Begin
SELECT
        accoutId ID_ACCOUNTS
--         , VDT.DF_DATES_FULL DT, V_FI_ANA_KEY.FI_DATE FA, V_FI_HISTORIES_KEY.FI_DATE HISFA
        ,Coalesce(VDT.DF_DATES_FULL, V_FI_ANA_KEY.FI_DATE) FI_DATE
        ,Coalesce(V_FI_HISTORIES_KEY.FI_OVERDUE, V_FI_ANA_KEY.FI_OVERDUE) FI_OVERDUE
        ,Coalesce(V_FI_HISTORIES_KEY.FI_NOT_OVERDUE, V_FI_ANA_KEY.FI_NOT_OVERDUE) FI_NOT_OVERDUE
    FROM DF_DATES VDT
    Left Join V_FI_ANA_KEY
        On VDT.DF_DATES_YEAR = EXTRACT(YEAR FROM V_FI_ANA_KEY.FI_DATE)
        AND VDT.DF_DATES_MONTH = MONTH(V_FI_ANA_KEY.FI_DATE)
        And V_FI_ANA_KEY.ID_ACCOUNTS = accoutId

    LEFT JOIN V_FI_HISTORIES_KEY
        On VDT.DF_DATES_YEAR = EXTRACT(YEAR FROM V_FI_HISTORIES_KEY.FI_DATE)
        AND VDT.DF_DATES_MONTH = MONTH(V_FI_HISTORIES_KEY.FI_DATE)
        And V_FI_HISTORIES_KEY.ID_ACCOUNTS = accoutId

    Where VDT.DF_DATES_DAY = 1
        AND VDT.DF_DATES_FULL < CURDATE()
        And VDT.DF_DATES_FULL >= beginDate
        And VDT.DF_DATES_FULL <= endDate
    ORDER BY FI_DATE ASC    
--     SELECT
--         'V_FI_ANA_KEY' src
--         , V_FI_ANA_KEY.ID_ACCOUNTS
--         , V_FI_ANA_KEY.FI_DATE
--         , V_FI_ANA_KEY.FI_OVERDUE
--         , V_FI_ANA_KEY.FI_NOT_OVERDUE
--     FROM V_FI_ANA_KEY
--     Where 
--         V_FI_ANA_KEY.ID_ACCOUNTS = accoutId
--         And V_FI_ANA_KEY.FI_DATE >= beginDate
--         And V_FI_ANA_KEY.FI_DATE <= endDate
--     UNION ALL
--     SELECT
--         'V_FI_HISTORIES_KEY' src
--         , accoutId ID_ACCOUNTS
--         ,VDT.DF_DATES_FULL FI_DATE
--         ,V_FI_HISTORIES_KEY.FI_OVERDUE FI_OVERDUE 
--         ,V_FI_HISTORIES_KEY.FI_NOT_OVERDUE FI_NOT_OVERDUE
--     FROM DF_DATES VDT
--     LEFT JOIN V_FI_HISTORIES_KEY
--         On VDT.DF_DATES_YEAR = EXTRACT(YEAR FROM V_FI_HISTORIES_KEY.FI_DATE)
--         AND VDT.DF_DATES_MONTH = MONTH(V_FI_HISTORIES_KEY.FI_DATE)
--         AND VDT.DF_DATES_FULL < CURDATE()
--         And V_FI_HISTORIES_KEY.ID_ACCOUNTS = accoutId
--     Where VDT.DF_DATES_DAY = 1
--         And VDT.DF_DATES_FULL >= beginDate
--         And VDT.DF_DATES_FULL <= endDate
-- 
--     ORDER BY FI_DATE ASC
    ;
end//
Delimiter ;