Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to improve a case statement that uses two columns

Tags:

tsql

I have a table called Purchase which has a State column, where 1 is authorized, 2 is completed (there are some other values too).

I also have a Retailer table, which has a column RetailerProcessType, where 1 is one-step and 2 is two-step.

I have the query below:

CASE purc.State     WHEN 1 THEN '"AUTHORISED"'     WHEN 2 THEN '"AUTHORISED"'     WHEN 4 THEN '"AUTHORISED"'     ELSE '"DECLINED"'  END                                                                       AS Autorised_Decline_Status, 

But what I need to do is as follows:

WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"' WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"' WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"' ELSE '"DECLINED"' 

The only way I can think of doing this is having a massive IF statement around the query, one for a one-step retailer and another for a two-step, as my understanding is a WHEN clause cannot have an AND in it.

However, this just seems long winded; anybody have any neater ideas?

like image 781
swade1987 Avatar asked Jan 19 '12 15:01

swade1987


People also ask

Can we use two columns in CASE statement in SQL?

Yes, you can evaluate different columns in the CASE statement.

Can you have multiple conditions in a CASE statement?

Multiple conditions in CASE statementYou can evaluate multiple conditions in the CASE statement.

Can we use aggregate function in CASE statement?

CASE statement in SQL and aggregate functions Aggregate functions in SQL Server perform calculations and return a single value. Examples of aggregate functions are MIN, MAX, COUNT, ABG and CHECKSUM. For this purpose, we use the COUNT aggregate function in SQL Server.


2 Answers

You could do it this way:

-- Notice how STATE got moved inside the condition: CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'      WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'      ELSE '"DECLINED"' END 

The reason you can do an AND here is that you are not checking the CASE of STATE, but instead you are CASING Conditions.

The key part here is that the STATE condition is a part of the WHEN.

like image 98
Bassam Mehanni Avatar answered Sep 30 '22 03:09

Bassam Mehanni


Just change your syntax ever so slightly:

CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'      WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'      WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'      ELSE '"DECLINED"' END 

If you don't put the field expression before the CASE statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.

like image 38
JNK Avatar answered Sep 30 '22 03:09

JNK