Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtraction between two sql queries

I have 2 queries in MS SQL that return a number of results using the COUNT function.

I can run the the first query and get the first result and then run the other one to get the other result, subtract them and find the results; however is there a way to combine all 3 functions and get 1 overall result

As in: run sql1 run sql2 run SQL3 (sql1-sql2)?....

I tried them with xxxx as a function but no luck.

like image 916
andreas Avatar asked Oct 19 '09 14:10

andreas


People also ask

How do I subtract two queries in SQL?

The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query.

Can we subtract two tables in SQL?

MINUS compares the data in two tables and returns only the rows of data using the specified columns that exist in the first table but not the second. It would be possible to get all of the results from the second table that don't exist in the first by switching the table order in the query.

How do you find the difference between two data in SQL?

SQL Server DIFFERENCE() Function The DIFFERENCE() function compares two SOUNDEX values, and returns an integer. The integer value indicates the match for the two SOUNDEX values, from 0 to 4. 0 indicates weak or no similarity between the SOUNDEX values.


2 Answers

You should be able to use subqueries for that:

SELECT     (SELECT COUNT(*) FROM ... WHERE ...)   - (SELECT COUNT(*) FROM ... WHERE ...) AS Difference 

Just tested it:

Difference ----------- 45  (1 row(s) affected) 
like image 145
Joey Avatar answered Oct 02 '22 22:10

Joey


SELECT (SELECT COUNT(*) FROM t1) - (SELECT COUNT(*) FROM t2) 
like image 32
Gary McGill Avatar answered Oct 02 '22 23:10

Gary McGill