This query makes one JOIN instead a LEFT join but I don’t know how do it
whitout the wheres clauses that uses cierre_mensual table:
SELECT last_odometro.equipo, IFNULL(SUM(cierre_mensual.recorrido),0) +
last_odometro.recorrido AS ultimo_odometro
FROM (
SELECT *
FROM `cierre_mensual`
WHERE mes < '2012-03-01'
AND `tipo_de_recorrido`
IN ( 1, 3 )
GROUP BY `equipo`
HAVING MAX( mes )
) AS last_odometro
LEFT JOIN
`cierre_mensual` ON last_odometro.`equipo` = cierre_mensual.`equipo`
WHERE
cierre_mensual.mes > last_odometro.mes
AND cierre_mensual.mes < '2012-03-01'
GROUP BY `last_odometro`.`equipo`
The table fields are:
id equipo mes combustible_en_tanque recorrido tipo_de_recorrido
1)I want to find recorrido whit the last mes(date) that tipo_de_recorrido are (1,3)
2)and sum the rest of the recorrido whith a bigger mes if exist
equipo mes combustible_en_tanque recorrido tipo_de_recorrido
7 2011-07-01 4 100 2
7 2011-07-01 4 100 2
7 2011-08-01 4 193900 1
7 2011-09-01 4 194000 1 <- the last row of type 1 194000
7 2011-10-01 4 100 2 +=100
7 2011-11-01 4 100 2 +=100
7 2011-12-01 4 100 2 +=100
7 2012-01-01 7 150 2 +=150
7 2012-02-01 4 50 2 +=50
Its returns:
equipo ultimo_odometro
7 195150
but if:
7 2011-07-01 4 100 2
7 2011-07-01 4 100 2
7 2011-08-01 4 193900 1
7 2011-09-01 4 194000 1 <- the last row of type 1 194000
no more rows whit type!=(1,2)
must return 194000 but the join fails.
You can move conditions from the
WHEREclause to theLEFT JOIN‘sONclause: