Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract Values from Two Different Tables

Tags:

sql

postgresql

Consider table X:

A
-
1
2
3
3
6

Consider table Y:

A
-
0
4
2
1
9

How do you write a query that takes the difference between these two tables, to compute the following table (say table Z):

A
-
1
-2
1
2
-3
like image 974
Boobie Avatar asked Mar 10 '11 02:03

Boobie


People also ask

How do you subtract values from different tables 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.


2 Answers

It's not clear what you want. Could it be this?

SELECT  (SELECT SUM(A) FROM X) - 
        (SELECT SUM(A) FROM Y)
        AS MyValue
like image 68
p.campbell Avatar answered Sep 20 '22 05:09

p.campbell


Marcelo is 100% right - in a true relational database the order of a result set is never guaranteed. that said, there are some databases that do always return sets in an order.

So if you are willing to risk it, here is one solution. Make two tables with autoincrement keys like this:

CREATE TABLE Sets (
  id integer identity(1,1)
, val decimal
) 

CREATE TABLE SetY (
  id integer identity(1,1)
, val decimal
) 

Then fill them with the X and Y values:

INSERT INTO Sets (val) (SELECT * FROM X)
INSERT INTO SetY (val) (SELECT * FROM Y)

Then you can do this to get your answer:

SELECT X.ID, X.Val, Y.Val, X.val-Y.val as Difference
FROM Sets X
LEFT OUTER JOIN SetY Y
  ON Y.id = X.ID

I would cross my fingers first though! If there is any way you can get a proper key in your table, please do so.

Cheers,

Daniel

like image 42
Daniel Williams Avatar answered Sep 20 '22 05:09

Daniel Williams