I'm sure it has to easier than what I'm doing, but I'm struggling to get this done. I need to get the expenses made for an ID on table A, but in case that ID exists on table B, the total expenses are the sum of all the rows with that ID on that table.
This is the query I'm using:
SELECT gastos.id,
gastos.importe,
SUM(asignacion_gastos.importe) AS "totalAsignado",
CASE
WHEN "totalAsignado" IS NULL THEN
"totalImporte" = gastos.importe
ELSE
"totalImporte" = "totalAsignado"
END
FROM gastos
LEFT JOIN asignacion_gastos
ON gastos.id = asignacion_gastos.idGasto
GROUP by gastos.id
ORDER BY gastos.id
I'm inserting this data in a Datatable, so, even if the the easiest solution would be to check it in the server side processing via PHP, I'd rather doing it in the query to run the app faster. (If I'm not wrong db queries are faster than PHP processing through thousands of results).