본문으로 건너뛰기
AUISoft에이유아이소프트
AUIPivot v2.8 DEMO

고객당 평균 매출

registerCustomAggregator

각 지점에서 고객 한 명이 평균적으로 얼마를 구매했는지 보여 줍니다. 매출 합계 ÷ 중복을 제외한 고객 수로 계산합니다.

예를 들어 A 고객이 10만 원과 20만 원, B 고객이 30만 원을 구매했다면 매출은 60만 원, 고객은 2명입니다. 고객당 평균 매출은 30만 원입니다.

registerCustomAggregator()로 이 계산을 등록하고, 등록한 id를 값 필드의 operation에 지정합니다. Set은 같은 고객 번호를 여러 번 넣어도 하나만 보관합니다.

원본에 고객 정보가 없어 연속된 판매기록 두 건에 같은 가상 고객 번호(CUSTOMER_ID)를 붙였습니다. 전체 자료에서는 240개 번호를 반복 사용하며, 실제 고객 통계는 아닙니다.

AUIPivot.registerCustomAggregator(myPivotID, {
    id: "CUSTOMER_AVG_SALES",
    version: 1,
    labelText: "고객당 평균 매출",
    // customerField에는 고객 번호가 들어 있는 필드 이름을 전달합니다.
    validateOptions: function (options, context) {
        context.requireField(options.customerField);
    },
    create: function () {
        // 매출을 더할 변수와 고객 번호를 모을 Set을 지점마다 따로 만듭니다.
        // Set에 같은 고객 번호를 여러 번 넣어도 하나만 남습니다.
        return { sales: 0, customers: new Set() };
    },
    accumulate: function (state, value, context) {
        // value는 이번 판매기록의 매출액(TOTAL)입니다.
        const customer = context.getValue(context.options.customerField);
        // 매출액과 고객 번호를 모두 확인할 수 있는 기록만 계산합니다.
        // 매출 0, 음수도 반영하며 고객 번호 자체는 바꾸지 않습니다.
        if (typeof value !== "number" || !Number.isFinite(value) ||
            typeof customer !== "string" || customer.trim() === "") return;
        state.sales += value;
        state.customers.add(customer);
    },
    merge: function (target, source) {
        // 총계에서도 매출은 더하고, 같은 고객은 한 번만 셉니다.
        // 지점별 고객 수나 평균을 단순히 더하면 중복 고객을 잘못 계산합니다.
        target.sales += source.sales;
        source.customers.forEach(function (customer) {
            target.customers.add(customer);
        });
    },
    finalize: function (state) {
        // 매출 합계 ÷ 중복을 제외한 고객 수. 고객이 없으면 빈칸입니다.
        return state.customers.size === 0 ? null : state.sales / state.customers.size;
    }
});

AUIPivot.setValueFields(myPivotID, [
    // 1. 모든 판매기록의 매출액을 더합니다.
    { dataField: "TOTAL", operation: "SUM", customLabelText: "매출 합계" },
    // 2. 고객 번호가 같은 기록은 한 고객으로 셉니다.
    { dataField: "CUSTOMER_ID", operation: "DISTINCT_COUNT", customLabelText: "고객 수(중복 제외)" },
    // 3. 위에서 등록한 계산으로 매출 합계를 고객 수로 나눕니다.
    {
        dataField: "TOTAL",
        operation: "CUSTOMER_AVG_SALES",
        aggregatorOptions: { customerField: "CUSTOMER_ID" },
        customLabelText: "고객당 평균 매출",
        formatString: "#,##0.00"
    }
]);

총 합계에서도 같은 고객은 한 명입니다. 여러 지점에서 구매한 고객이 있으므로 지점별 고객 수를 더한 값과 다를 수 있습니다.

함께 보기: 기준 가격 이상 차량의 판매 비중, 판매 대수 가중 평균, 고객별 매출 집중도

자동차 판매 자료를 불러오는 중입니다.