0

I am calculating a column based on existing tables column, but I don't know how to do that.

To explain my problem, let's say I have a table which has two columns A and B, both are int. What I am doing right now is

Select A,B (A-B)as C from Table

The check I want to apply is

if C is less then Zero it should show Zero. rather then a negative value.

What is the way to do this in SQL?

4 Answers 4

1
Select A,B,
CASE WHEN (A-B) < 0 THEN 0
ELSE (A-B)
END as C 
from Table
Sign up to request clarification or add additional context in comments.

Comments

1

You have to Use CASE (Transact-SQL)

This is what you want:

select A,B,
case when(A-B) < 0 then 0 else (A-B) end as c 
from Table

Demo: SQL Fiddle

Comments

1

Try this,

  Select A,B ,case when(A-B)< 0 then 0 else (A-B) end as C from Table;

Comments

-1
    try this

    select a,b,(a-b < 0 , 0 , a-b) as c from <table>
    // if then usage in mysql

    SELECT a,b,if(a-b < 0;0;a-b) as c FROM <table>
    // if then usage in sql

    // ie. if a-b is less than 0 then 0 else a-b 

1 Comment

FYI - the question is tagged with SQL Server, and specifically Transact-SQL. That uses CASE statements, rather than if-then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.