Oracle sql搜索行包含一个或多个关键字,并通过其关键字求和

时间:2015-04-30 05:26:58

标签: oracle subquery

我想用不同的文本计算sum,但是子查询不断返回多行而不是单行。 我是这样做的:

select sub.aid, 
sum (case when sub.text like '%abc' then sub.value end),
sum (case when sub.text like '%def' then sub.value end), ...

from (
   select a.aid, a.value, a.text
   from atable a, btable b
   where a.aid = b.bid and 
       a.aid = any (select aid
                 from atable
                 where text like '%abc' or text like '%def' or text like '%ghi' ....
                 group by aid
                 having count(*) >=1)
) sub
group by sub.aid

我得到ora-01427单行子查询返回多行错误。 我不知道问题是什么。如何使查询工作? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

让我们尝试将其分解,从最里面的查询开始,然后爬到最外面的查询。

在您最内层的查询中,having部分是多余的。如果count(*)为0,即使没有它,也不会获得任何行。话虽如此,此处不需要group by,而只需选择distinct

select distinct aid
from atable
where text like '%abc' or text like '%def' or text like '%ghi' ....

对于第二个查询:

  • 使用显式连接。您使用的连接方式已超过20年。
  • 我自己并不是一个甲骨文家伙,但我做了一些挖掘,事实证明any可能不是你想要的,你应该使用in代替。
  • 不清楚为什么使用btable的内部联接,除非确保在两个表中都存在任何结果。对我来说,看起来你是自我加入而btable是一个错字,应该是atable。然而,这更没意义。

在修复前2个点后,我们得到了这个查询:

select a.aid, a.value, a.text
from atable a 
inner join btable b on(a.aid = b.bid)
where a.aid in (
                select distinct aid
                from atable
                where text like '%abc' or text like '%def' or text like '%ghi' ....
               )

现在我希望你能看到,这基本上是一样的:

select a.aid, a.value, a.text
from atable a 
inner join btable b on(a.aid = b.bid)
where a.text like '%abc' or a.text like '%def' or a.text like '%ghi' ....

所以真的不需要最内层的查询。

转到最外面的查询:
再一次,有一些奇怪的野兔。我没有看到为group by添加一个查询包装中间查询的原因。此查询应该可以为您提供例外结果:

select a.aid, 
       sum (case when a.text like '%abc' then a.value end),
       sum (case when a.text like '%def' then a.value end), ...
from atable a 
inner join btable b on(a.aid = b.bid)
where a.text like '%abc' or a.text like '%def' or a.text like '%ghi' ....
group by a.aid
相关问题