<?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.iocoder.byzs.module.trade.dal.mysql.brokerage.BrokerageUserMapper">

    <select id="selectSummaryPageByUserId"
            resultType="cn.iocoder.byzs.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserChildSummaryRespVO">

        SELECT bu.id, bu.bind_user_time AS brokerageTime,
        (SELECT SUM(price) FROM trade_brokerage_record r
        WHERE r.user_id = bu.id AND biz_type = #{bizType} AND r.status = #{status} AND r.deleted = FALSE) AS brokeragePrice,
        (SELECT COUNT(1) FROM trade_brokerage_record r
        WHERE r.user_id = bu.id AND biz_type = #{bizType} AND r.status = #{status} AND r.deleted = FALSE) AS brokerageOrderCount,
        (SELECT COUNT(1) FROM trade_brokerage_user c
        WHERE c.bind_user_id = bu.id AND c.deleted = FALSE) AS brokerageUserCount
        FROM trade_brokerage_user AS bu
        <where>
            bu.deleted = false
            <if test="ids != null and ids.size() > 0">
                and bu.id in
                <foreach collection="ids" open="(" item="id" separator="," close=")">
                    #{id}
                </foreach>
            </if>
        </where>
        <choose>
            <when test="sortingField.field == 'userCount'">
                ORDER BY brokerageUserCount ${sortingField.order}
            </when>
            <when test="sortingField.field == 'orderCount'">
                ORDER BY brokerageOrderCount ${sortingField.order}
            </when>
            <when test="sortingField.field == 'price'">
                ORDER BY brokeragePrice ${sortingField.order}
            </when>
            <otherwise>
                ORDER BY bu.bind_user_time DESC
            </otherwise>
        </choose>
    </select>

</mapper>
