【问题标题】:I can't make this query work with SUM function我无法使此查询与 SUM 函数一起使用
【发布时间】:2011-02-10 12:03:35
【问题描述】:

此查询给出错误:

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 函数有关。我怎样才能使这项工作?提前感谢您的帮助。

【问题讨论】:

    标签: sql oracle ora-00904 ora-00979


    【解决方案1】:

    不幸的是,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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-19
      • 2014-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多