Search code examples
mysqlsqlmysql-error-1054mysql-5.5

Error 1054 on having clause with subquery joining with id grouped


got this query:

select 
T.id_empresa, max(periodo) as ultimoPeriodo, ( 
                        select sum(monto) from cuotasindical.pagos
                        where id_empresa = T.id_empresa and periodo = max(T.periodo)
                       ) as ultimoMonto, 
min(periodo) as periodoAnterior, (
                  select sum(monto) from cuotasindical.pagos
                  where id_empresa = T.id_empresa and periodo = min(T.periodo)
                   ) as anteriorMonto
from 
  (
    select 
    P1.id_empresa, P1.periodo, sum(monto) as monto
    from cuotasindical.pagos P1
    where P1.id_empresa in (select id_empresa from cuotasindical.empresa where id_delegacion = 5)
    group by P1.id_empresa, P1.periodo
    having P1.periodo in (
                select * from (
                                select periodo
                                from cuotasindical.pagos  
                                where P1.id_empresa = id_empresa order by periodo desc limit 2
                            ) as L
               )
    and count(distinct P1.periodo) > 1
  ) T
group by id_empresa
having (abs(max(monto) - min(monto))*100/
                    (
                      select sum(monto) from cuotasindical.pagos T2
                      where T2.id_empresa = id_empresa and T2.periodo = max(periodo)
                    ) > 10);

need to compare, for each empresa, the last two pagos (ordered by periodo) to see if they have a difference bigger or smaller than a percentage (in this case, 10)

I'm getting

Error Code: 1054. Unknown column 'P1.id_empresa' in 'where clause'

the only where clause there with that comparison, is the subquery with the limit

having P1.periodo in (
                select * from (
        select periodo
        from cuotasindical.pagos  
        where P1.id_empresa = id_empresa 
        order by periodo desc limit 2
        ) as L
               )
    and count(distinct P1.periodo) > 1

the double subquery is for avoid the limit 2 in the IN clause (get that on this link)

why I'm getting that error ? I thought that I can join after the group by in a subquery in having clause (just like a where clause)

or there is an error that I'm missing?

thanks in advance


Solution

  • the problem was that mysql has only one deep level of scope in subquerys.

    Also I have the problem of limit on subquery, so, what I do was

        ..having P1.periodo in 
        (
           select max(periodo) as periodo
           from cuotasindical.pagos H
           where P1.id_empresa = id_empresa 
        ) OR
        P1.periodo in (
           select max(periodo) as periodo
           from cuotasindical.pagos H
           where P1.id_empresa = id_empresa and periodo != P1.periodo
        )
    and count(distinct P1.periodo) > 1