<?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.ycwl.basic.mapper.ScenicDeviceStatsMapper">
    <!-- 插入景区设备统计记录 -->
    <insert id="insert" useGeneratedKeys="true" keyProperty="stats.id">
        REPLACE scenic_device_stats (
            scenic_id,
            device_id,
            date,
            count
        ) VALUES (
            #{stats.scenicId},
            #{stats.deviceId},
            #{stats.date},
            #{stats.count}
        )
    </insert>
    <select id="countDeviceStats"
            resultType="com.ycwl.basic.model.pc.scenicDeviceStats.entity.ScenicDeviceStatsEntity">
        select scenic_id, device_id, count(1) as count
        from (
            select s.scenic_id, s.device_id
            from member_source ms
            left join source s on ms.source_id = s.id
            where ms.type = 1 and s.id is not null
            and s.create_time >= #{start}
            and s.create_time &lt;= #{end}
            group by s.scenic_id, s.device_id, ms.face_id
        )a
        group by scenic_id, device_id
    </select>
    <select id="countCachedStatsByScenicId"
            resultType="com.ycwl.basic.model.pc.scenicDeviceStats.resp.ScenicDeviceStatsResp">
        select
        ds.scenic_id as scenicId,
        s.name as scenicName,
        ds.device_id as deviceId,
        d.name as deviceName,
        IFNULL(sum(ds.count), 0) as count
        from scenic_device_stats ds
        left join scenic s on ds.scenic_id = s.id
        left join device d on ds.device_id = d.id
        where s.id = #{scenicId}
        and ds.date >= #{start}
        and ds.date &lt;= #{end}
        group by ds.scenic_id, ds.device_id
    </select>
    <select id="countRealtimeStatsByScenicId"
            resultType="com.ycwl.basic.model.pc.scenicDeviceStats.resp.ScenicDeviceStatsResp">
        select
            ds.scenic_id as scenicId,
            s.name as scenicName,
            ds.device_id as deviceId,
            d.name as deviceName,
            ds.count
        from (
                 select scenic_id, device_id, count(1) as count
                 from (
                          select s.scenic_id, s.device_id
                          from member_source ms
                                   left join source s on ms.source_id = s.id
                          where ms.type = 2 and s.id is not null
                            and s.create_time >= #{start}
                            and s.create_time &lt;= #{end}
                          group by s.scenic_id, s.device_id, ms.face_id
                      )a
                 group by scenic_id, device_id
             ) ds
                 left join scenic s on ds.scenic_id = s.id
                 left join device d on ds.device_id = d.id
        where s.id = #{scenicId}
    </select>
</mapper>