ORACLE SQL从2个select语句中获取两个值的差异

时间:2012-09-05 07:24:38

标签: sql oracle select oracle10g

我们有2个非常简单的SELECT语句:

SELECT value from table where date between DATE1 and DATE2
SELECT value from table where date between DATE3 and DATE4

我们需要一种方法来编写单个SQL语句,它将获得从这两个SQL语句返回的“值”的差异。

我们尝试了以下但是没有成功:

SELECT value from table where date between DATE1 and DATE2
minus 
SELECT value from table where date between DATE3 and DATE4

任何建议都非常感谢。

6 个答案:

答案 0 :(得分:16)

未经测试但应该有效:

SELECT
    (SELECT value from table where date between DATE1 and DATE2) - 
    (SELECT value from table where date between DATE3 and DATE4)
FROM dual;

假设您的SELECT value保证返回单个值

答案 1 :(得分:2)

SELECT value FROM TBL WHERE date BETWEEN DATE1 and DATE2 
AND value NOT IN (SELECT value FROM TBL WHERE date BETWEEN DATE3 AND DATE4)

答案 2 :(得分:2)

如果您认为您的内部查询可以提供多个值,请使用下面的

SELECT
    (SELECT sum(value) from table where date between DATE1 and DATE2) - 
    (SELECT sum(value) from table where date between DATE3 and DATE4) as answer
FROM dual;

答案 3 :(得分:1)

请试试这个:

SET SERVEROUTPUT ON
DECLARE
V_FIRST NUMBER := 0;
V_SECOND NUMBER := 0;
BEGIN
  SELECT value into V_FIRST from table where rownum=1 and date between DATE1 and DATE2;
  SELECT value into V_SECOND from table where rownum=1 and date between DATE3 and DATE4;

  DBMS_OUTPUT.PUT_LINE (V_FIRST-V_SECOND); 
END;

答案 4 :(得分:1)

(
SELECT value from table where date between DATE1 and DATE2
 minus 
SELECT value from table where date between DATE3 and DATE4
)
union all
(
SELECT value from table where date between DATE3 and DATE4
 minus 
SELECT value from table where date between DATE1 and DATE2
)

答案 5 :(得分:1)

以下声明适用于您的案例

(
SELECT value from table where date between DATE3 and DATE4
 minus 
SELECT value from table where date between DATE1 and DATE2
)
union
(
SELECT value from table where date between DATE1 and DATE2
 minus 
SELECT value from table where date between DATE3 and DATE4
)