/*
 * mg_abovavg_dbio.pgc - mg 모듈 DB 접근 함수 (mg_abovavg_dbio), archived into libmgdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * 채널 평균금액을 초과한 전문 건수 (상관 서브쿼리 avg).
 */
#include <string.h>
#include <userlog.h>
#include "mg_abovavg_dbio.h"

long mgdb_above_chan_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 mg_msg_log m
        WHERE m.biz_date = :h_bizdate
          AND m.amount > (SELECT avg(m2.amount) FROM mg_msg_log m2
                          WHERE m2.channel = m.channel AND m2.biz_date = :h_bizdate);
    if (sqlca.sqlcode < 0) return -1;
    return h_v;
}
