1

此查询给出错误:

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

错误:ORA-00904:“类型”:标识符无效

当我使用 运行它时group by ep,错误消息变为:

ORA-00979: 不是 GROUP BY 表达式

如果我删除行sum(b2b_d+b2b_t-b2b_i) as sales和,整个查询工作正常group by ...,所以问题应该与 SUM 和 GROUP BY 函数有关。我怎样才能使这项工作?在此先感谢您的帮助。

4

1 回答 1

4

不幸的是,SQL 不允许您在 GROUP BY 子句中使用列别名,因此您要么必须像这样重复整个 CASE:

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

或使用这样的内联视图:

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
于 2010-04-21T08:43:37.823 回答