<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jkcredit.invoice.hub.mapper.ConsumptionStatisticsMapper">

    <select id="getConsumptionStatistics" resultType="com.jkcredit.invoice.hub.model.po.record.ConsumptionStatisticsPo">
        select
        user.app_key,
        user.company,
        start.startAmount,
        end.endAmount,
        invoiceResult.invoiceAmount,
        invoiceResult.totalAmount,
        invoiceResult.totalTaxAmount,
        charge.chargeAmount
        from h_user user
        left join(select start.user_id, count(*) startAmount
        from h_car_free_carrier_bill_start start
        where start.activated = 1
        group by start.user_id) start on user.id = start.user_id
        left join (select end.user_id, count(*) endAmount
        from h_car_free_carrier_bill_end end
        where end.activated = 1
        group by end.user_id) end on user.id = end.user_id
        left join (select result.user_id,
        count(*) as invoiceAmount,
        sum(total_amount) as totalAmount,
        sum(total_tax_amount) as totalTaxAmount
        from h_search_invoice_result result
        where result.activated = 1
        group by result.user_id) invoiceResult
        on user.id = invoiceResult.user_id
        left join (select charge.user_id, count(*) chargeAmount
        from h_real_charge charge
        group by charge.user_id) charge on user.id = charge.user_id
        <where>
            user.activated = 1 and user.user_type = 2
            <if test="query.appKey != null and query.appKey != ''">
                and user.app_key = #{query.appKey}
            </if>
            <if test="query.company != null and query.company != ''">
                and user.company like CONCAT('%',#{query.company},'%')
            </if>
        </where>
    </select>
</mapper>
