I need to execute some SQL that looks like this:
select approve_firm_id,approve_dt,approve_result
from main_approve
group by approve_firm_id
having MAX(approve_dt) and approve_result=0;
it runs (mysql-5.1), but if I try in the Django model like this:
Approve.objects.annotate(max_dt=Max('approve_dt')).
filter(max_dt__gt=0).filter(approve_result=0).query
The query generated is this:
SELECT `main_approve`.`id`, `main_approve`.`approve_result`,
`main_approve`.`approve_dt`, `main_approve`.`approve_user_id`,
`main_approve`.`approve_firm_id`, `main_approve`.`exported_at`,
MAX(`main_approve`.`approve_dt`) AS `max_dt` FROM `main_approve`
WHERE (`main_approve`.`approve_result` = 0 )
GROUP BY `main_approve`.`id`
HAVING MAX(`main_approve`.`approve_dt`) > 0
ORDER BY NULL
I need the WHERE clause to be AFTER the GROUP BY clause.