/*
 * st_feehaving_dbio.pgc - 고수수료 다건 가맹점 (st_feehaving_dbio), libstdbio.a.
 * ECPG; GROUP BY merchant_id HAVING sum(amount) > a AND count(*) > c 커서로 대상 가맹점 수.
 */
#include <string.h>
#include <userlog.h>
#include "st_feehaving_dbio.h"

long stdb_high_fee_merchants(const char *bizdate, long amt_thr, long cnt_thr)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_mid[32];
    long h_amt = amt_thr, h_cnt = cnt_thr, h_sum, h_n, merchants = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE fhc CURSOR FOR
        SELECT merchant_id, sum(amount), count(*) FROM st_settle_dtl
        WHERE biz_date = :h_bizdate GROUP BY merchant_id
        HAVING sum(amount) > :h_amt AND count(*) > :h_cnt;
    EXEC SQL OPEN fhc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH fhc INTO :h_mid, :h_sum, :h_n;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE fhc; return -1; }
        merchants++;
    }
    EXEC SQL CLOSE fhc;
    return merchants;
}
