<?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.njzscloud.supervisory.tsp.mapper.TempStoragePointMapper">

    <select id="statistics" resultType="com.njzscloud.supervisory.tsp.pojo.TempStoragePointStatisticsResult">
        SELECT latest.total_count,
               IF(latest.total_count = 0, 0.00,
                  IF(previous.total_count = 0, 100.00,
                     ROUND((latest.total_count - previous.total_count) / previous.total_count * 100, 2)
                  )
               ) AS total_count_growth_rate,

               latest.online_count,
               IF(latest.online_count = 0, 0.00,
                  IF(previous.online_count = 0, 100.00,
                     ROUND((latest.online_count - previous.online_count) / previous.online_count * 100, 2)
                  )
               ) AS online_count_growth_rate,

               latest.offline_count,
               previous.offline_count,
               IF(latest.offline_count = 0, 0.00,
                  IF(previous.offline_count = 0, 100.00,
                     ROUND((latest.offline_count - previous.offline_count) / previous.offline_count * 100, 2)
                  )
               ) AS offline_count_growth_rate
        FROM (SELECT MAX(IF(t = 1, c, 0)) total_count,
                     MAX(IF(t = 2, c, 0)) online_count,
                     MAX(IF(t = 3, c, 0)) offline_count
              FROM (SELECT COUNT(*) c, 1 t
                    FROM temp_storage_point
                    UNION ALL
                    SELECT COUNT(*) c, 2 t
                    FROM temp_storage_point
                    WHERE status = 'ZhengChang'
                    UNION ALL
                    SELECT COUNT(*) c, 3 t
                    FROM temp_storage_point
                    WHERE status = 'FenZhengChang') t) AS latest
                 CROSS JOIN
             (SELECT MAX(IF(t = 1, c, 0)) total_count,
                     MAX(IF(t = 2, c, 0)) online_count,
                     MAX(IF(t = 3, c, 0)) offline_count
              FROM (SELECT COUNT(*) c, 1 t
                    FROM temp_storage_point
                    WHERE create_time &lt;= LAST_DAY(CURRENT_DATE - INTERVAL 1 MONTH)

                    UNION ALL

                    SELECT COUNT(*) c, 2 t
                    FROM temp_storage_point
                    WHERE status = 'ZhengChang'
                      AND create_time &lt;= LAST_DAY(CURRENT_DATE - INTERVAL 1 MONTH)

                    UNION ALL

                    SELECT COUNT(*) c, 3 t
                    FROM temp_storage_point
                    WHERE status = 'FenZhengChang'
                      AND create_time &lt;= LAST_DAY(CURRENT_DATE - INTERVAL 1 MONTH)) t) AS previous
    </select>
</mapper>
