<?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.ningdatech.carapi.car.rpt.mapper.RptMonthOverspeedSpecialVehiclesMapper">

<select id="reportPage" resultType="com.ningdatech.carapi.car.rpt.model.po.RptMonthSpecialOfflinePO">
    <!--根据传入的排名条件筛选对应的企业数据-->
    select
    tt.region_id,
    tt.overspeedCurrentTimes,
    tt.overspeedLastTimes,
    tt.maxOverspeedRate
    from
    <!--根据传入的(最高)超速率条件筛选对应的企业车辆数据-->
    (select
    st.region_id,
    st.overspeedCurrentTimes,
    st.overspeedLastTimes,
    st.maxOverspeedRate
    from
    (select
    ft.region_id,
    ft.overspeedCurrentTimes,
    ft.overspeedLastTimes,
    ft.maxOverspeedRate
    from
    <!--从车辆超速信息表中查出专有车辆区域ID、（车辆）本月超速次数、（车辆）上月超速次数、最大超速率-->
    (select
    o.region_id,
    count(case when o.overspeed_date between #{param.startTime} and #{param.endTime}  then 1 end) overspeedCurrentTimes,
    count(case when o.overspeed_date between #{param.lastMonthStartTime} and #{param.lastMonthEndTime}  then 1 end) overspeedLastTimes,
    max(ifnull(round((o.max_speed - o.limit_speed) / o.limit_speed * 100,2),0)) as maxOverspeedRate
    from nd_vehicle_overspeed_info as o
    left join nd_vehicle_base_info as b on o.car_plate = b.car_plate
    left join nd_region as r on o.region_id = r.id
    left join nd_company_info as c on o.company_id = c.id
    where o.deleted = 0 and o.max_speed is not null and o.limit_speed is not null and
    b.deleted = 0 and b.audit_state = 2 and b.vehicle_type in (1,2,3,4)
    <if test="param.startTime != null and param.endTime != null">
        and o.overspeed_date
        between concat(#{param.startTime},' 00:00:00') and concat(#{param.endTime},' 23:59:59')
    </if>
    ${param.dataScopeSql}
    group by o.region_id
    order by overspeedLastTimes desc,overspeedCurrentTimes desc
    ) as ft
    where 1 = 1
    <if test="param.startRate != null">
        and maxOverspeedRate &gt;= #{param.startRate}
    </if>
    <if test="param.endRate != null">
        and maxOverspeedRate &lt;= #{param.endRate}
    </if>
    ) as st
    ) as tt
</select>
</mapper>
