<?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.openhis.administration.mapper.TraceNoManageMapper">
    <select id="getItemTraceNoInfo" resultType="com.openhis.administration.domain.TraceNoManage">
        SELECT item_table,
               item_id,
               location_id,
               lot_number,
               trace_no,
               MAX(create_time)
        FROM adm_trace_no_manage
        WHERE item_table = #{itemTable}
          AND item_id = #{itemId}
          AND location_id = #{locationId}
          AND lot_number = #{lotNumber}
          AND (trace_no) IN (
            SELECT trace_no
            FROM adm_trace_no_manage
            WHERE item_table = #{itemTable}
              AND item_id = #{itemId}
              AND location_id = #{locationId}
              AND lot_number = #{lotNumber}
              AND delete_flag = '0'
            GROUP BY trace_no
            HAVING SUM(CASE WHEN status_enum = 1 THEN 1 ELSE 0 END) > -- 进库次数
                   SUM(CASE WHEN status_enum = 2 THEN 1 ELSE 0 END) -- 出库次数
        )
          AND delete_flag = '0'
        GROUP BY item_table,
                 item_id,
                 location_id,
                 lot_number,
                 trace_no
    </select>
</mapper>