ORACLE将两个查询合并为一个查询

ORACLE将两个查询合并为一个查询,oracle,Oracle,我正在尝试连接两个查询,其中唯一的区别在于子句RECIP like'44%==>RECIP not like'44%,并且具有唯一的输出 select FIELD1, FIELD2, FIELD3-PART, sum(c) from ( select FIELD1, FIELD2, SUBSTR(FIELD3, 1, 2) as FIELD3-PART, count(*) as c from table where timestamp between sysdate -

我正在尝试连接两个查询,其中唯一的区别在于子句
RECIP like'44%==>RECIP not like'44%
,并且具有唯一的输出

   select FIELD1, FIELD2, FIELD3-PART, sum(c) from
   ( select FIELD1, FIELD2, SUBSTR(FIELD3, 1, 2) as FIELD3-PART, count(*) as c from
    table
   where timestamp between sysdate - interval '120' minute and sysdate - interval '2' minute 
   FIELD3 is not null and FIELD3 like '44%'
   group by FIELD1, FIELD2, FIELD3)
   group by FIELD1, FIELD2, FIELD3-PART
   HAVING ((sum(c) > '150' and SUBSTR(ORIG, 1,6)='333441')  
   or (sum(c) > '100' and SUBSTR(FIELD2, 1,6)='333442')      
   or (sum(c) > '250' and SUBSTR(FIELD2, 1,6)='333443')
   or (sum(c) > '10' and SUBSTR(FIELD2, 1,6)='333444'));
   
   select FIELD1, FIELD2, FIELD3-PART, sum(c) from
   ( select FIELD1, FIELD2, SUBSTR(FIELD3, 1, 2) as FIELD3-PART, count(*) as c from
    table
   where timestamp between sysdate - interval '120' minute and sysdate - interval '2' minute 
   FIELD3 is not null and FIELD3 not like '44%'
   group by FIELD1, FIELD2, FIELD3)
   group by FIELD1, FIELD2, FIELD3-PART
   HAVING ((sum(c) > '150' and SUBSTR(ORIG, 1,6)='333441')  
   or (sum(c) > '100' and SUBSTR(FIELD2, 1,6)='333442')      
   or (sum(c) > '250' and SUBSTR(FIELD2, 1,6)='333443')
   or (sum(c) > '10' and SUBSTR(FIELD2, 1,6)='333444')); 
我知道确实有更“优雅”的方式来执行查询并获得所需的输出,但我不是sql专家,实际上这两个查询工作得非常完美。 非常感谢。
Lucas

您可以将查询更新为-

select FIELD1,
       FIELD2,
       FIELD3-PART,
       sum(c)
  from (select FIELD1,
               FIELD2,
               SUBSTR(FIELD3, 1, 2) as FIELD3-PART,
               count(*) as c
          from table
         where timestamp between sysdate - interval '120' minute and sysdate - interval '2' minute 
           -- AND FIELD3 is not null        -- No need to use this line as LIKE predicate automatically filters null values.
           and FIELD3 like '44%'
         group by FIELD1, FIELD2, SUBSTR(FIELD3, 1, 2))
 group by FIELD1, FIELD2, FIELD3-PART
HAVING sum(c) > '50' 
   and SUBSTR(ORIG, 1,6) IN ('333441', '333442', '333443', '333444');

我仍然怀疑您的查询是否有效,因为在您的查询中没有所谓的ORIG(在HAVING子句中使用),我可以看到。

您可以使用UNION吗?是的,我可以,但基本上使用UNION我将有两个查询。因为我有相同的字段,只有一个不同的子句,所以可以将quesy调整为一个yes,我的拼写错误,ORIG是FIELD2。让我试试你的解决方案,现在谢谢。编辑:请注意,有计数总是不同的,我相信你的代码不适合我的需要。我将尝试调整它,再次感谢您编辑:您的查询将只处理字段3,如“44%”,我错了吗?在这两次编辑之后,我需要像'44%'一样的字段3和像'44%'一样的字段3,我认为您的查询是完美的。我不这样认为,您的查询似乎只处理子句上的'44%',所以这对我来说不好,因为我需要喜欢和不喜欢。我的意思是,在您上面建议的两次编辑之后,您使用的查询非常好。请放弃我的查询并继续使用您的查询。