I have table with statistical data.
I’m trying to count the records grouped by a version, the problem is that the records have another criteria (ref) and should counted only once (per ref).
stats sample data to illustrate the issue:
id stat_date ref version
-------------------------
1 2012-01-25 1 A
2 2012-01-25 2 B
3 2012-01-25 3 A
4 2012-01-26 8 B
5 2012-01-26 2 B
6 2012-01-26 3 B <-- version has been updated for ref=3
Simple counting would return
SELECT COUNT(*),version FROM stat GROUP BY version
1,A
5,B
The problem here is that only the last record with ref=3 (id=6) should be counted and (id=3) has to be ignored.
So the question is, how can I filter row (id=3) from the query?
I can’t figure out what I should insert as condition in the subquery
SELECT COUNT(*),version FROM stats
WHERE stat_date BETWEEN "2012-01-25" AND "2012-01-26"
AND id = (SELECT MAX(id) FROM stats WHERE <condition>)
GROUP BY 2
The expected result would be:
1,A (since id=3 is ignored)
3,B (since the first id=2 is ignored and only id=5 is taken into account)
Try:
EDIT: Not guaranteed to always work: