<?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="cn.iocoder.yudao.module.iot.dal.mysql.deviceoperationrecord.DeviceOperationRecordMapper">

    <!--
        一般情况下，尽可能使用 Mapper 进行 CRUD 增删改查即可。
        无法满足的场景，例如说多表关联查询，才使用 XML 编写 SQL。
        代码生成器暂时只生成 Mapper XML 文件本身，更多推荐 MybatisX 快速开发插件来生成查询。
        文档可见：https://www.iocoder.cn/MyBatis/x-plugins/
     -->

    <select id="deviceOperationPage"
            resultType="cn.iocoder.yudao.module.iot.controller.admin.deviceoperationrecord.vo.DeviceTotalTimeRecordRespVO">
        SELECT
        ide.device_code as deviceCode,
        ide.device_name as deviceName,
        SUM(CASE WHEN idor.rule = '1' THEN idor.total_running_time ELSE 0 END) AS totalRunningTime,
        SUM(CASE WHEN idor.rule = '2' THEN idor.total_standby_time ELSE 0 END) AS totalStandbyTime,
        SUM(CASE WHEN idor.rule = '3' THEN idor.total_fault_time ELSE 0 END) AS totalFaultTime,
        SUM(CASE WHEN idor.rule = '4' THEN idor.total_warning_time ELSE 0 END) AS totalWarningTime
        FROM besure.iot_device_operation_record idor
        LEFT JOIN besure.iot_device ide ON idor.device_id = ide.id
        WHERE idor.rule IN ('1', '2', '3', '4')
        AND idor.deleted = 0
        <!-- 时间筛选条件 -->
        <if test="pageReqVO.startTime != null">
            AND idor.create_time &gt;= #{pageReqVO.startTime}
        </if>
        <if test="pageReqVO.endTime != null">
            AND idor.create_time &lt;= #{pageReqVO.endTime}
        </if>
        <!-- 设备编码筛选条件 -->
        <if test="pageReqVO.deviceCode != null and pageReqVO.deviceCode != ''">
            AND ide.device_code LIKE CONCAT('%', #{pageReqVO.deviceCode}, '%')
        </if>
        <!-- 设备名称筛选条件 -->
        <if test="pageReqVO.deviceName != null and pageReqVO.deviceName != ''">
            AND ide.device_name LIKE CONCAT('%', #{pageReqVO.deviceName}, '%')
        </if>
        GROUP BY ide.id, ide.device_code, ide.device_name
        ORDER BY ide.device_code
    </select>
</mapper>