<?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.securityManagement.trainingCourseRecord.mapper.HotTrainingCourseRecordMapper">

    <select id="selectPersonalAnnualRecordCourses"
            resultType="com.hotwj.platform.securityManagement.trainingCourseRecord.domain.vo.PersonalAnnualRecordCourseVo">
        WITH plan_base AS (
        SELECT DISTINCT p.training_id AS trainingId,
        COALESCE(t.start_time, t.create_time) AS planTime,
        t.class_hours AS classHours
        FROM hot_training_participant p
        INNER JOIN hot_training t
        ON t.id = p.training_id
        AND t.is_deleted = 0
        WHERE p.user_id = #{userId}
        AND p.is_deleted = 0
        <if test="trainingType != null and trainingType != ''">
            AND t.training_type = #{trainingType}
        </if>
        AND COALESCE(t.start_time, t.create_time) &gt;= #{startTime}
        AND COALESCE(t.start_time, t.create_time) &lt; #{endTime}
        ),
        course_ranked AS (
        SELECT r.training_id AS trainingId,
        COALESCE(cfg.course_name, c.name, CONCAT('课程', r.training_course_id)) AS courseName,
        ROW_NUMBER() OVER (
        PARTITION BY r.training_id
        ORDER BY COALESCE(r.complete_time, r.create_time) ASC, r.id ASC
        ) AS seq
        FROM hot_training_course_record r
        LEFT JOIN hot_training_course_config cfg
        ON cfg.id = r.training_course_id
        AND cfg.is_deleted = 0
        LEFT JOIN hot_course c
        ON c.id = cfg.course_id
        AND c.is_deleted = 0
        WHERE r.user_id = #{userId}
        AND r.is_deleted = 0
        ),
        course_agg AS (
        SELECT trainingId,
        GROUP_CONCAT(CONCAT(seq, '.', courseName) ORDER BY seq SEPARATOR '\n') AS courseName
        FROM course_ranked
        GROUP BY trainingId
        )
        SELECT COALESCE(a.courseName, '') AS courseName,
        DATE_FORMAT(b.planTime, '%Y.%m.%d') AS trainingTime,
        '及格' AS evaluation,
        CAST(b.classHours AS CHAR) AS hours
        FROM plan_base b
        LEFT JOIN course_agg a
        ON a.trainingId = b.trainingId
        ORDER BY b.planTime ASC
    </select>
</mapper>
