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;
请回答您的问题,并添加一些示例数据和基于该数据的预期输出。请您的问题-不要在评论中发布代码或附加信息。