question

billj avatar image
billj asked

How to subtract values from same table but different columns

Hello, I need to subtract columns C and B (C-B) from a table. Here is the query to create the table. CREATE TABLE My_TABLE1 ( A int, B nvarchar(10), C nvarchar(10) ) INSERT INTO My_TABLE1 VALUES (12,'--','8'), (7,'2', '.03'), (3, '.03','4'), (10, '3','5'), (18, '--','7') Here is the output. SELECT * FROM My_TABLE1 ![alt text][1] When subtract 'C - B' the fourth column will show the difference. ![alt text][2] [1]: /storage/temp/3921-result.png [2]: /storage/temp/3922-result2.png Thank you for your help.
sql-server-2012
result.png (4.5 KiB)
result2.png (5.1 KiB)
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
JohnM avatar image
JohnM answered
Something like this should work: SELECT [a], [b], [c], CASE [b] WHEN '--' THEN b ELSE CAST(CAST(c AS DECIMAL(5,2)) - CAST(b AS DECIMAL(5,2)) AS NVARCHAR(5)) END AS Diff_C_B FROM dbo.My_Table1 go It's worth noting though if you are going to store numbers and do math on them it would be better to store them at numeric data types (int, decimal, numeric, etc) other wise you'll have to do a CAST/CONVERT on them with the values you have in the [B] column. Hope that helps.
5 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

billj avatar image billj commented ·
John, Works perfectly. Thanks so much for your time and help.
0 Likes 0 ·
JohnM avatar image JohnM commented ·
Awesome! If that solved your issue, please make sure to mark it as the answer know so that others know your question was answered.
0 Likes 0 ·
billj avatar image billj commented ·
John, Where is the place to check this question as answered?
0 Likes 0 ·
JohnM avatar image JohnM commented ·
There should be a button you can click next to the answer that I provided.
0 Likes 0 ·
billj avatar image billj commented ·
OK. Thanks.
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.