/*
 * cl_wavg_dbio.pgc - cl 모듈 DB 접근 함수 (cl_wavg_dbio), archived into libcldbio.a.
 * 건수 가중 평균 gross (weighted average).
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "cl_wavg_dbio.h"

/* 스냅샷 gross 를 txn_count 로 가중한 평균 = sum(gross*cnt)/sum(cnt). */
long clqdb_wavg_gross(long cid)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_cid = cid, h_num = 0, h_den = 0;
    EXEC SQL END DECLARE SECTION;
    EXEC SQL SELECT coalesce(sum(gross_amount * txn_count),0), coalesce(sum(txn_count),0)
        INTO :h_num, :h_den FROM cl_snapshot WHERE close_id = :h_cid;
    if (sqlca.sqlcode < 0) return -1;
    if (h_den <= 0) return 0;
    return h_num / h_den;
}
