Domanda

Questa query dà un errore:

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

Errore: ORA-00904: "TIPO": non valido identificativo

Quando eseguo con group by ep, il messaggio di errore diventa:

ORA-00979: non un GROUP BY espressione

L'intera query funziona bene se mi tolgo la sum(b2b_d+b2b_t-b2b_i) as sales linee e group by ..., in modo che il problema dovrebbe essere correlato alle funzioni SUM e GROUP BY. Come posso fare questo lavoro? Grazie in anticipo per il vostro aiuto.

È stato utile?

Soluzione

Purtroppo SQL non consente di utilizzare gli alias di colonna nella clausola GROUP BY, in modo da avere sia per ripetere l'intero caso c'è in questo modo:

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 utilizzare una vista in-line in questo modo:

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top