Pregunta

Esta consulta da un error:

select ep, 
  case
    when ob is null and b2b_ob is null then 'a'
    when ob is not null or b2b_ob is not null then 'b'
    else null
  end as type,
  sum(b2b_d + b2b_t - b2b_i) as sales
from table
where ...
group by ep, type

Error: ORA-00904: "TIPO": inválido identificador

Cuando corro con group by ep, el mensaje de error se convierte en:

ORA-00979: no es una expresión GROUP BY

La consulta todo funciona bien si quito el sum(b2b_d+b2b_t-b2b_i) as sales líneas y group by ..., por lo que el problema debe estar relacionado con las funciones SUM y GROUP BY. ¿Cómo puedo hacer este trabajo? Gracias de antemano por su ayuda.

¿Fue útil?

Solución

Desafortunadamente SQL no permite utilizar los alias de columnas en la cláusula GROUP BY, así que o bien tiene que repetir todo el caso de que de esta manera:

select ep, 
  case
    when ob is null and b2b_ob is null then 'a'
    when ob is not null or b2b_ob is not null then 'b'
    else null
  end as type,
  sum(b2b_d + b2b_t - b2b_i) as sales
from table
where ...
group by ep,
  case
    when ob is null and b2b_ob is null then 'a'
    when ob is not null or b2b_ob is not null then 'b'
    else null
  end

o usar una visión en línea como la siguiente:

select ep, 
  type,
  sum(b2b_d + b2b_t - b2b_i) as sales
from
( select ep, 
    case
      when ob is null and b2b_ob is null then 'a'
      when ob is not null or b2b_ob is not null then 'b'
      else null
    end as type,
    b2b_d,
    b2b_t,
    b2b_i
  from table
  where ...
)
group by ep, type
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top