/*
 * rc_derived_dbio.pgc - rc 모듈 DB 접근 함수 세트 (rc_derived_dbio), archived into librcdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * 파생 테이블(FROM 서브쿼리) - 매입별 대사건수의 평균.
 */
#include <string.h>
#include <userlog.h>
#include "rc_derived_dbio.h"

long rcdb_avg_match_per_purchase(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 coalesce(round(avg(c)),0) INTO :h_v FROM (
        SELECT purchase_id, count(*) AS c FROM rc_match_log
        WHERE biz_date = :h_bizdate GROUP BY purchase_id) t;
    if (sqlca.sqlcode < 0) { userlog("rcdb_avg_match_per_purchase FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    return h_v;
}
