-- Data gaps: enabled devices with no position_history or trips in last 7 days
SELECT
    d.imei,
    d.device_name,
    d.enabled_flag,
    MAX(ph.gps_time)   AS last_position,
    MAX(t.start_time)  AS last_trip
FROM tracksolid.devices d
LEFT JOIN tracksolid.position_history ph
       ON ph.imei = d.imei
      AND ph.gps_time > NOW() - INTERVAL '7 days'
LEFT JOIN tracksolid.trips t
       ON t.imei = d.imei
      AND t.start_time > NOW() - INTERVAL '7 days'
WHERE d.enabled_flag = 1
GROUP BY d.imei, d.device_name, d.enabled_flag
HAVING MAX(ph.gps_time) IS NULL
   AND MAX(t.start_time) IS NULL
ORDER BY d.imei;
