Search code examples
sqlpostgresqlselectcoalesce

Error near select using coalesce on postgresql


I have this query

select  bpl.id_employee as employeeId, 
    round(
        (
            sum(bppgt.nu_hours) + (sum(bppgt.nu_minutes::decimal)/60)
        ) - 
        coalesce(select sum(nu_horas), 0) 
            from boemulsa_sindical_hours 
            where fe_fecha_inicio >= '2019/12/01' 
            and fe_fecha_inicio <= '2019/12/31', 2) as hours,
    bri.nu_cod_incidence as incidenceCode, 
    min(bppgt.fe_date) as date
    from productions_people_general_tasks bppgt
    left join people bpl on bpl.id_employee = bppgt.id_employee
    left join general_tasks bgt on bgt.id_task = bppgt.id_task
    left join rrhh_incidences bri on bri.id_incidence = bgt.id_incidence
    where bppgt.fe_date >= '2019/12/01'         
    group by  bpl.id_employee
    order by bpl.id_employee

And I have this error, any ideas on what I'm doing wrong?

ERROR:  error de sintaxis en o cerca de «select»
LINE 6:    coalesce(select sum(nu_horas), 0) 

Thanks in advance!


Solution

  • A subquery requires its own set of parentheses. However, an aggregation query with no group by always returns exactly one row. So you can move the coalesce() inside the subuqery:

       (select coalesce(sum(nu_horas), 0) 
        from boemulsa_sindical_hours 
        where fe_fecha_inicio >= '2019/12/01'  and
              fe_fecha_inicio <= '2019/12/31'
       )