Click here to Skip to main content
15,891,372 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to subtract two values in sql from the multiple table for example we subtract two values in same table table Name=tbl1 and fields are a=column1 and b=column2
like =sum as column1-column2
Now my question is that how to subtract the two values from different column
example i have two table table1=tbl1 and table2=tbl2
in tbl1 i have column A,b &
in tbl2 i have column c

now i want thing like this= c as tbl1.a-tbl1.b
Posted
Comments
phil.o 30-Sep-15 15:27pm    
What have you tried?

1 solution

If I understand your question correctly, you need to create a query where you join the tables. After doing that you can do the calculation.

Consider the following example
SQL
SELECT t1.A,
       t1.B,
       t2.C,
       t1.A - t1.B - t2.C AS Calculation
FROM Table1 t1 INNER JOIN Table2 t2
     ON t1.ParentColumn = t2.ChildColumn

For more information about the joins, have a look at Visual Representation of SQL Joins[^]

ADDITION

If this is to be an update situation for for example Table1.D then consider the following example
SQL
UPDATE t1
SET D = t1.A - t1.B - t2.C
FROM Table1 t1 INNER JOIN Table2 t2
     ON t1.ParentColumn = t2.ChildColumn

For info about using joins in update statements, see UPDATE[^]
Another variation could be for example
SQL
UPDATE Table1
SET D = (SELECT Table1.A - Table1.B - t2.C
         FROM Table2 t2
         WHERE Table1.ParentColumn = t2.ChildColumn)

Note that this must return only one value per each row in Table1 so if the relation is one-to-many you need to restrict the query or use aggregates such as SUM
 
Share this answer
 
v3
Comments
Member 11963532 30-Sep-15 15:28pm    
and how to update the result in tbl1 field c
Wendelius 30-Sep-15 15:34pm    
Have a look at the updated solution
Member 11963532 30-Sep-15 15:37pm    
thank you soo much Mr Mika Wendelius you always help me thnx for thaat again and again and lottttsss
Member 11963532 30-Sep-15 16:07pm    
bro its can't be update because the first table column field is competed and the error is showing like this,,,,
The column "remaing_income" cannot be modified because it is either a computed column or is the result of a UNION operator.
Member 11963532 30-Sep-15 16:08pm    
bro Mika Wendelius its can't be update because the first table column field is competed and the error is showing like this,,,,
The column "remaing_income" cannot be modified because it is either a computed column or is the result of a UNION operator.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900