I have the following table below. I'm trying to retrieve data and group them by name, I then want only the latest row according to the created_at column. I ran the query below and seem to get getting what I want. However, when I add more weights, the query sometimes omits the some data. What is going on???
"id" "name" "value" "created_at" "animal_id"
"6" "body_condition_score" "9" "2022-02-26" "1"
"9" "body_condition_score" "8" "2022-02-27" "1"
"7" "dental_score" "4" "2022-02-25" "1"
"10" "dental_score" "1" "2022-03-25" "1"
"11" "dental_score" "5" "2022-03-25" "2"
"4" "heart_rate" "1500""2022-02-25" "1"
"5" "respiratory_rate" "20" "2022-02-25" "1"
"2" "weight" "90.52" "2022-02-22" "1"
"3" "weight" "99" "2022-02-23" "1"
"13" "weight" "0" "2022-02-21" "1"
"12" "weight" "1" "2022-02-25" "2"
SELECT vitals.*
FROM vitals
INNER JOIN
(
SELECT `name`, `value`, MAX(created_at) created_at
FROM vitals
GROUP BY `name`
) grouped
ON grouped.`name` = vitals.`name`
AND grouped.created_at = vitals.created_at
WHERE animal_id = 1
"id" "name" "value" "created_at" "animal_id"
"4" "heart_rate" "1500" "2022-02-25" "1"
"5" "respiratory_rate" "20" "2022-02-25" "1"
"9" "body_condition_score" "8" "2022-02-27" "1"
"10" "dental_score" "1" "2022-03-25" "1"