Oracle sql 搜索包含一个或多个关键字的行并按其关键字求和

Oracle sql search rows containing one or more keyword and sum by its keyword

我想通过不同的文本计算总和,但子查询一直返回多行,而不是单行。 我是这样做的:

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 单行子查询 returns 多行错误。 我不知道是什么问题。我如何获得查询工作? 提前致谢。

让我们试着分解它,从最内层的查询开始,向上爬到最外层的查询。

在您最内层的查询中,having 部分是多余的。如果 count(*) 为 0,即使没有它,您也不会得到任何行。话虽如此,这里不需要 group by,您可以简单地 select distinct:

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

对于第二个查询:

  • 使用显式连接。您使用的联接样式已过时 20 多年。
  • 我自己不是 oracle 人,但我做了一些挖掘,结果发现 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