<?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.hotwj.platform.workbench.mapper.HotTrainingDailyStatsMapper">

    <insert id="upsertDailyStats">
        INSERT INTO hot_training_daily_stats (company_id,
                                              stats_date,
                                              total_count,
                                              completed_count,
                                              uncompleted_count,
                                              create_time,
                                              update_time,
                                              is_deleted)
        SELECT tp.company_id                  AS company_id,
               #{statsDate}                   AS stats_date,
               COUNT(*)                       AS total_count,
               SUM(CASE
                       WHEN tp.is_completed = 1 AND tp.complete_time IS NOT NULL AND tp.complete_time &lt;= #{dayEnd}
                           THEN 1
                       ELSE 0 END)            AS completed_count,
               COUNT(*) - SUM(CASE
                                  WHEN tp.is_completed = 1 AND tp.complete_time IS NOT NULL AND
                                       tp.complete_time &lt;= #{dayEnd}
                                      THEN 1
                                  ELSE 0 END) AS uncompleted_count,
               NOW(),
               NOW(),
               0
        FROM hot_training_participant tp
                 INNER JOIN sys_company c
                            ON c.id = tp.company_id
                                AND c.is_deleted = 0
                                AND c.status = 1
        WHERE tp.is_deleted = 0
          AND tp.create_time IS NOT NULL
          AND tp.create_time &lt;= #{dayEnd}
        GROUP BY tp.company_id ON DUPLICATE KEY
        UPDATE
            total_count =
        VALUES (total_count), completed_count =
        VALUES (completed_count), uncompleted_count =
        VALUES (uncompleted_count), update_time = NOW(), is_deleted = 0
    </insert>

    <select id="selectByCompanyAndDateRange" resultType="com.hotwj.platform.workbench.domain.vo.TrainingDailyStatsVo">
        SELECT stats_date        AS statsDate,
               completed_count   AS completedCount,
               uncompleted_count AS uncompletedCount
        FROM hot_training_daily_stats
        WHERE is_deleted = 0
          AND company_id = #{companyId}
          AND stats_date BETWEEN #{startDate} AND #{endDate}
        ORDER BY stats_date ASC
    </select>
</mapper>
