我在Oracle中如何做到这一点?
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
但foo不是一个已识别的变量。
答案 0 :(得分: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 )
答案 1 :(得分: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
非常合适的情况。