/*
 * ac_install_corr_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_install_corr_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: 상관(correlated) 서브쿼리 - 동일 매입의 평균 월납입액을 초과한 회차 수.
 */
#include <string.h>
#include <userlog.h>
#include "ac_install_corr_dbio.h"

/* 같은 purchase_id 의 평균 month_amount 를 초과하는 할부 회차 건수. */
long acdb_install_above_own_avg(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_v = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT count(*) INTO :h_v FROM ac_install i
        WHERE i.biz_date = :h_bizdate
          AND i.month_amount > (SELECT avg(j.month_amount) FROM ac_install j
                                WHERE j.purchase_id = i.purchase_id);
    if (sqlca.sqlcode < 0) return -1;
    return h_v;
}
