Hello,
First here is the SQL statement which worked on my end:
SELECT CURRENT_DATE AS "Today's Date", TO_CHAR("Overdue",'MM/DD/YY') AS "Past Due",
"treatment_type" || ' ' || "treatment_subtype" AS "Treatment",
RIGHT (100000 + CAST("dog_id" AS VARCHAR(4)),4) || ' ' || "name" AS "Dog"
FROM "dog" "d"
JOIN (SELECT "dog_id", "treatment_type", "treatment_subtype",
MAX("due_date") "Overdue"
FROM "dt"
GROUP BY "dog_id", "treatment_type",
"treatment_subtype") A ON "d"."dog_id" = "A"."dog_id"
WHERE (CURRENT_DATE > "Overdue")
AND "name" IN ('Bali','Dana','Fred','Pep','Pedro','Stumpy')
The only item which may error is the table name dt. I used this as there is confusion on the treatment table name.
Now the what & why. So the first thing actually done is to get valid ‘Treatment’ records. This was a main concern until I realized your thinking was askew. What you want here is the record with the highest date (the MAX select) and not only grouped by ‘dog_id’ but also by ‘treatment_type’ and ‘treatment_subtype’. Now once this base is established, join it to the ‘dog’ table and make the selections (WHERE conditions) from there.
The other item of note is the date. The MAX portion leaves it as an absolute date & the TO_CHAR puts it in a viewable format.
If this answers your question please tick the
(upper left area of answer). It helps others to know there was an accepted answer.