eatonphil
eatonphil

Reputation: 13682

SQL Case when something AND something THEN

Is possible to have an and statement in a SQL CASE clause? If so how do you write it?

i.e something like this?:

CASE
    When ((Column < 1) AND (Column2 > 0)) THEN column4 + 1
END as Column

my code that executes but doesn't accomplish what i want (have no negative numbers):

CASE
WHEN (((Clean_Total_Time - ActivityTimeTotalMin) < 0) AND (ActivityTimeTotalMin > 0))     
THEN (ABS(DATEDIFF(hh,Total_Time,ActivityTotalTime))-1)
END as hours

my code that does work and does accomplish what it should but I don't want it because it allows for negative numbers:

CASE
WHEN (Clean_Total_Time - ActivityTimeTotalMin) < 0
THEN (ABS(DATEDIFF(hh,Total_Time,ActivityTotalTime))-1)
END as hours

EDIT: The purpose of this calculation is as follows:

It subtracts two columns, and if the result is negative, is subtracts the number one from one of those two columns. Further, my AND section was to say that if that column had a value of zero, then it would not subtract 1 from the column. I don't want that column to have numbers below zero.

The only thing that is not happening, is that it is not catching if the column is equal to zero. So I am getting negative 1 whenever there was originally a 0.

Upvotes: 2

Views: 2464

Answers (1)

Kermit
Kermit

Reputation: 34055

According to this MSDN article it is:

SELECT ProductNumber, Name, "Price Range" = 
      CASE 
         ...
         WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
         WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
         ELSE 'Over $1000'
      END
FROM Production.Product

I just don't think you need the parentheses.

Update 1

You can try using CASE inside CASE like so:

CASE
    WHEN Column < 1
        CASE
            WHEN Column2 > 0 THEN column4 + 1
        END
END AS Column

Upvotes: 2

Related Questions