Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 733
Sanath Avatar asked Sep 05 '12 07:09

Sanath


5 Answers

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

like image 175
jsj Avatar answered Oct 28 '22 03:10

jsj


SELECT value FROM TBL WHERE date BETWEEN DATE1 and DATE2 
AND value NOT IN (SELECT value FROM TBL WHERE date BETWEEN DATE3 AND DATE4)
like image 35
Samson Avatar answered Oct 28 '22 03:10

Samson


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;
like image 29
dinesh salve Avatar answered Oct 28 '22 02:10

dinesh salve


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;
like image 1
TechDo Avatar answered Oct 28 '22 03:10

TechDo


(
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
)
like image 1
schurik Avatar answered Oct 28 '22 01:10

schurik