/*
 * rc_amtwindow_dbio.pgc - rc 유형별 최고금액 순위 (rc_amtwindow_dbio), librcdbio.a.
 * ECPG; 호출자 XA 브랜치에서 수행, EXEC SQL CONNECT 없음.
 * 윈도우 rank() OVER (PARTITION BY match_type ORDER BY amount DESC) 로 유형별 1순위 건수.
 */
#include <string.h>
#include <userlog.h>
#include "rc_amtwindow_dbio.h"

long rcdb_top_amount_per_type(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_type[24];
    long h_rank, h_amt, tops = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE awc CURSOR FOR
        SELECT match_type, amount,
               rank() OVER (PARTITION BY match_type ORDER BY amount DESC)
        FROM rc_match_log WHERE biz_date = :h_bizdate;
    EXEC SQL OPEN awc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH awc INTO :h_type, :h_amt, :h_rank;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE awc; return -1; }
        if (h_rank == 1) tops++;
    }
    EXEC SQL CLOSE awc;
    return tops;
}
