<?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="cn.pluss.platform.mapper.MerchantBillStatisticsMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="cn.pluss.platform.entity.MerchantBillStatistics">
        <id column="id" property="id" />
        <result column="userId" property="userId" />
        <result column="startDate" property="startDate" />
        <result column="endDate" property="endDate" />
        <result column="type" property="type" />
        <result column="amount" property="amount" />
        <result column="count" property="count" />
        <result column="remark" property="remark" />
        <result column="createTime" property="createTime" />
        <result column="updateTime" property="updateTime" />
    </resultMap>

    <insert id="insertDuringBill">
        INSERT IGNORE INTO tb_pluss_merchant_bill_statistics(userId, startDate, endDate, type, amount, count)
        SELECT ua.userId, #{startDate}, #{endDate}, "1", IFNULL(t.amount, 0), IFNULL(t.count, 0)
        FROM
            tb_pluss_user_app ua LEFT JOIN
            (
                SELECT
                    t.merchantCode,
                    SUM(
                        IF( `status` = '1', consumeFee, -consumeFee )
                        ) amount,
                    SUM(
                        IF( `status` = '1', 1, 0 )
                        ) count
                FROM
                    (
                    SELECT
                        merchantCode, `status`, consumeFee,
                        DATE_FORMAT( createDt, "%Y-%m-%d" ) createTime
                    FROM tb_pluss_merchant_order
                    WHERE `status` IN ( '1', '2' )
                    AND createDt &gt;= CONCAT(#{startDate}, " 00:00:00")
                    AND createDt &lt;= CONCAT(#{endDate}, " 23:59:59")
                    ) t
                GROUP BY
                    t.merchantCode
            ) t ON t.merchantCode = ua.merchantCode
            LEFT JOIN tb_pluss_merchant_channel_status mcs ON ua.merchantCode = mcs.merchantCode
        WHERE ua.userType = 'promoter' AND mcs.`status` = '3' AND mcs.updateTime &lt;= CONCAT(#{endDate}, " 23:59:59" )
    </insert>
</mapper>
