2012-12-03 50 views
1

我有一个在Oracle中如何做到这一点?如何创建包含分组字段的oracle where子句?

select a.field1 || '_' || 
     b.field2 || '_' || 
     sum(c.field3) 
    from table1 a, 
     table2 b, 
     table3 c 
where a.field1 || '_' || 
     b.field2 || '_' || 
     sum(c.field3) not in (select d.field1 || '_' || 
            e.field2 || '_' || 
            sum(f.field3) 
           from table4 d, 
            table5 e, 
            table6 f 
           where conditional_info_to_join_the_tables 
           group by d.field1, e.field2) 
    and conditional_info_to_join_the_tables 
group by a.field1, b.field2 

我得到的错误是,我不能在where子句

我一直在使用

select a.field1 || '_' || 
     b.field2 || '_' || 
     sum(c.field3), 
     sum(c.field2) foo 
    from table1 a, 
     table2 b, 
     table3 c 
where a.field1 || '_' || 
     b.field2 || '_' || 
     foo not in (select d.field1 || '_' || 
          e.field2 || '_' || 
          sum(f.field3) 
        from table4 d, 
          table5 e, 
          table6 f 
        where conditional_info_to_join_the_tables 
        group by d.field1, e.field2) 
    and conditional_info_to_join_the_tables 
group by a.field1, b.field2 

试图使用sum但富不是一个确定的变量。

回答

3

仅仅给sum和别名(foo)没有帮助的,因为总的滤波(在where条款后发生

having条款就是这样聚集后应用过滤器:

select a.field1 || '_' || b.field2 || '_' || sum(c.field3) 
from table1 a, table2 b, table3 c 
where conditional_info_to_join_the_tables 
group by a.field1, b.field2 
having a.field1 || '_' || b.field2 || '_' || sum(c.field3) 
      not in (select d.field1 || '_' || e.field2 || '_' || sum(f.field3) 
        from table4 d, table5 e, table6 f 
        where conditional_info_to_join_the_tables 
        group by d.field1, e.field2) 

你仍然需要完整地写出聚合而不是别名 - 背后的原因有点不太明显,并在dba.se的这个答案中讨论:https://dba.stackexchange.com/a/21982/1396

当然你也可以达到同样的使用子查询:

select foo 
from(select a.field1 || '_' || b.field2 || '_' || sum(c.field3) as foo 
     from table1 a, table2 b, table3 c 
     where conditional_info_to_join_the_tables 
     group by a.field1, b.field2) 
where foo not in (select d.field1 || '_' || e.field2 || '_' || sum(f.field3) 
        from table4 d, table5 e, table6 f 
        where conditional_info_to_join_the_tables 
        group by d.field1, e.field2) 
+0

感谢您清理那个 –

0

你可以做到这一点没有所有的连接:

select abc.field1 || '_' || abc.field2 || '_' || sumf, 
     sum(c.field2) foo 
from (select a.field1, b.field2, sum(c.field3) as sumf 
     from a, b, c 
     where conditional_info_to_join_the_tables 
     group by a.field1, b.field2 
    ) abc left outer join 
    (select d.field1, e.field2, sum(f.field3) as sumf 
     from d, e, f 
     where conditional_info_to_join_the_tables 
     group by d.field1, 3.field2 
    ) def 
    on abc.field1 = def.field1 and 
     abc.field2 = def.field2 and 
     abc.sumf = def.sumf 
where def.field1 = NULL 

您应该使用更现代化的join语法,一般。这是left outer join非常合适的情况。