Dos cosas.
Primero, si deja de usar WHERE MONTH(wydatki.data_zakupu) = MONTH(CURRENT_DATE())
al elegir tus fechas obtendrás tres ventajas.
- Tu búsqueda de fechas será sargable :un índice lo acelerará.
- Obtendrá un esquema más general para elegir meses.
- Si tiene datos de varios años en sus tablas, todo funcionará mejor.
En su lugar, en general utilice este tipo de expresión para buscar el mes actual. Ya te diste cuenta de la mayor parte de esto.
WHERE wydatki.data_zakupu >= LAST_DAY(CURRENT_DATE()) + INTERVAL 1 DAY - INTERVAL 1 MONTH
AND wydatki.data_zakupu < LAST_DAY(CURRENT_DATE()) + INTERVAL 1 DAY - INTERVAL 0 MONTH
Esto busca todos los valores de fecha y hora en o después de la medianoche del primer día del mes actual, y antes, pero no en <
, medianoche del primer día del próximo mes.
Se generaliza a cualquier mes que desee. Por ejemplo,
WHERE wydatki.data_zakupu >= LAST_DAY(CURRENT_DATE()) + INTERVAL 1 DAY - INTERVAL 2 MONTH
AND wydatki.data_zakupu < LAST_DAY(CURRENT_DATE()) + INTERVAL 1 DAY - INTERVAL 1 MONTH
te recibe el mes pasado. Esto también funciona cuando el mes actual es enero y funciona cuando tiene datos de varios años en sus tablas.
Estas expresiones son un poco detalladas porque MySQL no tiene un FIRST_DAY(date)
función, solo a LAST_DAY(date)
función
. Así que necesitamos todas las que + INTERVAL 1 DAY
negocio de los monos
.
En segundo lugar, extraer los datos de un mes anterior es tan simple como agregar otro LEFT JOIN ( SELECT...
cláusula a su mesa, así. (http://sqlfiddle.com/#!9/676df4/13
)
SELECT ...
coalesce(month1.tot, 0) AS LastMonth
FROM wydatki_kategorie cat
LEFT JOIN
...
LEFT JOIN
(SELECT wydatki_wpisy.kategoria,
sum(wydatki_wpisy.brutto) AS tot
FROM wydatki_wpisy
LEFT JOIN wydatki ON wydatki_wpisy.do_wydatku = wydatki.id_wydatku
WHERE wydatki.data_zakupu >= LAST_DAY(CURRENT_DATE()) + INTERVAL 1 DAY - INTERVAL 2 MONTH
AND wydatki.data_zakupu < LAST_DAY(CURRENT_DATE()) + INTERVAL 1 DAY - INTERVAL 1 MONTH
AND wydatki.id_kupujacy = 1
GROUP BY wydatki_wpisy.kategoria
) month1 ON cat.id_kat = month1.kategoria
Como puede ver, el intervalo de fechas WHERE
la cláusula aquí obtiene las filas del mes anterior.