I’m fairly decent and writing SQL queries, but my brain has been spinning trying to figure out a the best way to write a query. Here is the setup:
Table Animals has columns: animal_id, farmer_id, type, born_on
This table has tons of rows in it, recording all animal births for each farmer.
What I need to do is get all farmer_ids of farmers where of the 10 most recent animal births for them, at least 3 of are of type “sheep.”
Any help is appreciated!
This was my try:
SELECT a.farmer_id
FROM Animals a
WHERE
(select count(game_id)
from Animals b
where b.farmer_id = a.farmer_id
ORDER BY born_on DESC LIMIT 10) >= 3
This is a little more difficult because MySQL doesn’t have Row_Number() so you’ll need to simulate it. One way is use a self join and a count. You could also use the
@rownumbertechnique described hereIn my example I used animal_id to find the most recent but you may want to change the JOIN condition to
AND t1.born_on < t2.born_onDEMO
SAMPLE Data used
The result is only 2 because even though 3 has three sheep they weren’t in the last 10