Query SQL to subtract two fields

前端 未结 3 1627
感情败类
感情败类 2020-12-21 21:02

My query is that I have two tables, one called sec_users with the following fields:

pk_user, name, dias_disponibles

And anothe

3条回答
  •  旧时难觅i
    2020-12-21 21:13

    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;
    

提交回复
热议问题