ORACLE SQL get difference of two values retrieved from 2 select statements

眉间皱痕 提交于 2019-12-22 04:56:38

问题


We have 2 very simple SELECT statements:

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

We need a way to write a single SQL statement which will get the difference of the "value" that is returned from these two SQL statements.

We tried the following but it was not successful:

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

Any suggestion is highly appreciated.


回答1:


Untested but should work:

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

Assuming that your SELECT value is guaranteed to return a single value




回答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)



回答3:


If you think your inner queries can give multiple values, use below

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;



回答4:


Please try this:

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;



回答5:


(
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
)



回答6:


Below statement should work for your case

(
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
)


来源:https://stackoverflow.com/questions/12276459/oracle-sql-get-difference-of-two-values-retrieved-from-2-select-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!