DROP VIEW IF EXISTS v_animals_weight_alerts; CREATE VIEW v_animals_weight_alerts AS SELECT a.id AS animal_id, -- dernier poids ( SELECT m.value FROM measurements m WHERE m.animal_id=a.id AND m.type='weight' ORDER BY m.id DESC LIMIT 1 ) AS last_weight, -- poids de référence ~30 jours avant : le plus récent <= J-30 ( SELECT m.value FROM measurements m WHERE m.animal_id=a.id AND m.type='weight' AND date(m.measured_at) <= date('now','-30 day') ORDER BY date(m.measured_at) DESC, m.id DESC LIMIT 1 ) AS w30_weight, ( SELECT m.measured_at FROM measurements m WHERE m.animal_id=a.id AND m.type='weight' AND date(m.measured_at) <= date('now','-30 day') ORDER BY date(m.measured_at) DESC, m.id DESC LIMIT 1 ) AS w30_date FROM animals a;