Click here to Skip to main content
15,039,244 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Anyone here who knows on how to subtract two columns in same table? I have columns: total amount and cash tendered. Now I want to subtract that 2 columns and display the result as a another column. How to do that?

Table:
try7 — imgbb.com[^]

What I have tried:

SELECT MAX(trans_cash) - MIN(trans_total) FROM tbltransactions;
Posted
Updated 19-Mar-18 6:15am
v2
Comments
CHill60 19-Mar-18 12:17pm
   
If they are varchar types then change them now - use the correct datatype for values. Numeric data does not belong in text columns.
Get rid of the max and min (unless you are trying to do something "clever")
Please don't use images to post data like this, it's quite easy to paste that into your question

1 solution

Simple: change your DB.
If you have numeric values, then store them in numeric columns. If you don;t then you set yourself up for problems, and the later you leave it before you bite teh bullet and fix the actual problem the worth the problem will get and the harder it is to fix.

Don't use VARCHAR or NVARCHAR for anything other than string data - store numbers in INT, FLOAT, or DECIMAL columns, store dates in DATE, DATETIME, or DATETIME2 columns. And problems like this just melt away...

You could fix it for this specific case by CASTing the NVARCHAR data to an integer, but the query will fail if any column contains a non-numeric value ... much better to fix the data problem instead!
   
Comments
John Th 20-Mar-18 2:30am
   
Should I change the varchar datatype to decimal(6,2)?
OriginalGriff 20-Mar-18 5:33am
   
That should work.

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