Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 重写/改进此查询的其他方法_Sql_Oracle_Oracle11g - Fatal编程技术网

Sql 重写/改进此查询的其他方法

Sql 重写/改进此查询的其他方法,sql,oracle,oracle11g,Sql,Oracle,Oracle11g,是否有其他方法重写/改进此查询,尽量减少输入错误,并尽可能提高性能: Select (Select Sum(value) from table1 where code = 'B2' and date between DATE '2017-01-01' and DATE '2017-03-31') + (Select Sum(value) from table2 where code = 'B2' and date bet

是否有其他方法重写/改进此查询,尽量减少输入错误,并尽可能提高性能:

Select 
 (Select Sum(value) from table1
  where code = 'B2' 
    and date between DATE '2017-01-01' 
                 and DATE '2017-03-31')
   +
 (Select Sum(value) from table2
  where code = 'B2' 
    and date between DATE '2017-04-01' 
                 and DATE '2017-04-30')
我也尝试过使用union all,但这仍然不是我需要的:

Select Sum(value) 
  from (Select code, value from table1 
        Where date between DATE '2017-01-01' 
                       and DATE '2017-03-31')
  union all 
       (Select code, value from table1 
        Where date between DATE '2017-04-01'
                   and DATE '2017-04-30')
 where code = 'B2'

谢谢你的第一个问题很好。假设您在末尾有一个来自dual的


对于性能,您需要在
表1(代码、日期、值)
表2(代码、日期、值)
上建立索引。请注意,索引中列的顺序很重要。

如果使用typo表示查询中有两次条件代码='B2',则可以将其移动到from子句中。无论如何,请注意子查询可以返回NULL。使用
NVL
(或
COALESCE
)处理此问题

select 
  nvl((select sum(value) from table1 
       where code = x.code and date between date '2017-01-01' and date '2017-03-31'), 0)
   +
  nvl((select sum(value) from table2
       where code = x.code and date between date '2017-04-01' and date '2017-04-30'), 0)
from (select 'B2' as code from dual) x;
请回答您的问题,并添加一些示例数据和基于该数据的预期输出。请您的问题-不要在评论中发布代码或附加信息。