My query is that I have two tables, one called sec_users
with the following fields:
pk_user, name, dias_disponibles
And anothe
Use SUM aggregating function:
SELECT u.pk_user, sum(u.dias_disponibles) - sum(s.n_diassolicitados) AS dias_libres
FROM sec_users u
LEFT JOIN solicitud s
on s.fk_empleado = u.pk_user
GROUP BY u.pk_user
...and always follow tip 1 from comments!
The user1 creates another request for 2 days of sick leave, those 2 days of sick leave do not count as requested days. How can I show those two days requested, using the following code:
SELECT u.pk_user, u.dias_disponibles - sum(s.n_diassolicitados) AS dias_libres
FROM sec_users u
LEFT JOIN solicitud s
on s.fk_empleado = u.pk_user
GROUP BY u.pk_user
You want to subtract the sum of n_diassolicitados
from the dias_disponibles
. So don't join the table solicitud
, but the aggregation query:
SELECT
u.pk_user,
u.dias_disponibles - COALESCE(s.dias_solicitados, 0) AS dias_libres
FROM sec_users u
LEFT JOIN
(
SELECT fk_empleado, SUM(n_diassolicitados) AS dias_solicitados
FROM solicitud
GROUP BY fk_empleado
) s on s.fk_empleado = u.pk_user;