I was testing the query below thinking it would get me around the "can’t use LIMIT in subqueries" restriction. The query runs but the average is simply the average of all the records WHERE MScores.MemberId=1193 AND MScores.Div
="FSO"
It seems to completely ignore the EXISTS clause.
The query should return the rolling average of the 5 (or less) most recent scores for a specific member in a specific division.
Any ideas why the EXISTS clause fails to affect the results?
SELECT MScores.MemberId, MScores.`Div`, AVG(MScores.Final) AS AvgOfFinal
FROM qryMatchScores MScores
WHERE MScores.MemberId=1193 AND MScores.`Div`="FSO" AND
EXISTS (
SELECT MatchDate
FROM qryMatchScores MDates
WHERE
MDates.MemberId = MScores.MemberId AND
MDates.`Div` = MScores.`Div` AND
MDates.MatchDate = MScores.MatchDate
ORDER BY MatchDate DESC
LIMIT 5
);
3
Answers
You are trying to do two separate and incompatible things in your exists subquery: select the most recent 5 dates, and filter by the date of the outer row. You can’t have both. The closest thing to your approach I can come up with is:
Without some sample data and coresponding expected result, It’s hard to tell what you want to do. Another thing not completely explained is your statement:
As far as I understood it – this is something that could be solved using Avg() Over() analytic function with windowing clause and Row_Number() to handle ordering (and scope if needed) …
… SQL getting rolling (running) average in both ways ordered by date and an average of all rows fetched …
… if you want to filter (limit) the whole thing to just 5 latest rows per id – just add WHERE clause to outer query …
See the fiddle here.
NOTE:
Depending on your actual data, you’ll need to add Division column to Partition By clause (with MemberId) of analytic functions (in case that 1 MemberId could be with 2 Divisions) OR to do the Division filtering in WHERE clause (if 1 MemberId is always with 1 Division) …
It would help if you tried row_number()