此查询出错:
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:“TYPE”:标识符无效
当我使用group by ep
运行时,错误消息变为:
ORA-00979:不是GROUP BY表达式
如果删除行sum(b2b_d+b2b_t-b2b_i) as sales
和group by ...
,整个查询都可以正常工作,因此问题应与SUM和GROUP BY函数相关。我怎样才能做到这一点?在此先感谢您的帮助。
答案 0 :(得分: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