I have the following query, the variable a works well if I don’t use an ORDER BY clause:
set @a:=0;
SELECT doc, @a as before, movement as mov, (@a:=@a+movement) as after, date
FROM movements m
LEFT JOIN (
SELECT doc, 1 as tdoc, date
FROM invoices
UNION ALL
SELECT doc, 2 as tdoc, date
FROM nulled
) sub
ON m.doc=sub.doc and m.doc_type = sub.tdoc
WHERE m.product_id="XXXX"
so I get something like:
DOC BEFORE MOVEMENT AFTER DATE
006 0 10 10 2012-07-01
008 10 -3 7 2012-07-03
015 7 5 12 2012-06-20
But I want the movements to be ordered by date so I included ORDER BY date at the end of the query and I get:
DOC BEFORE MOVEMENT AFTER DATE
015 7 5 12 2012-06-20
006 0 10 10 2012-07-01
008 10 -3 7 2012-07-03
instead of what I want:
DOC BEFORE MOVEMENT AFTER DATE
015 0 5 5 2012-06-20
006 5 10 15 2012-07-01
008 15 -3 12 2012-07-03
Is there a way to get this? the variable is being calculated and afterwards the results are ordered. Is there a way to force that the results are ordered first and then the variable is calculated?
Have you tried moving the ordering on subquery?
e.g.