Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional CASE statement syntax

I need help writing a case statement for a view. The base table has 2 columns that I'll be referencing: 'Stage' and 'YesNo'.

If Stage column is 1, and the YesNo column is 1, I need the CASE statement to show it in the view as 'No.' If the Stage column is 1, and the YesNo column is 0, I need the CASE statement to show it in the view as 'Yes.' If the Stage column is 1, and the YesNo column is NULL, I need the CASE statement to show it in the view as NULL. If the Stage is anything other than 1, I need the YesNo column to show in the view as NULL.

This is my logic so far which I think is correct, but when I try to run it, I get a syntax error about the word 'AS'. Any suggestions?

CASE 
    WHEN a.Stage = 1 and a.YesorNo = 1 THEN 'No' 
    ELSE WHEN a.Stage = 1 and a.YesorNo = 0 THEN 'Yes' 
END AS NewViewColumn
like image 879
dp3 Avatar asked Dec 12 '12 14:12

dp3


People also ask

Which of the following is the syntax for CASE statement?

Which of the following is correct syntax for CASE statement? Explanation: The CASE statement is started with the keyword CASE followed by any identifier or expression and the IS.

What is the conditional syntax in SQL?

A condition specifies a combination of one or more expressions and logical (Boolean) operators and returns a value of TRUE , FALSE , or unknown.

How do you write a CASE in a select statement?

The CASE statement always goes in the SELECT clause. CASE must include the following components: WHEN , THEN , and END . ELSE is an optional component. You can make any conditional statement using any conditional operator (like WHERE ) between WHEN and THEN .


2 Answers

Remove the ELSE WHEN, if you leave the ELSE out then it will return null for any items not meeting the remaining logic:

CASE 
    WHEN a.Stage = 1 and a.YesorNo = 1 THEN 'No' 
    WHEN a.Stage = 1 and a.YesorNo = 0 THEN 'Yes' 
END AS NewViewColumn

Or use:

CASE 
    WHEN a.Stage = 1 and a.YesorNo = 1 THEN 'No' 
    WHEN a.Stage = 1 and a.YesorNo = 0 THEN 'Yes' 
    ELSE 'other'
END AS NewViewColumn
like image 105
Taryn Avatar answered Sep 22 '22 13:09

Taryn


CASE 
  WHEN a.Stage = 1 and a.YesorNo = 1 THEN 'No'   
  WHEN a.Stage = 1 and a.YesorNo = 0 THEN 'Yes'
  ELSE something else  -- If you ignored this it will be NULL
END AS NewViewColumn
like image 35
Mahmoud Gamal Avatar answered Sep 21 '22 13:09

Mahmoud Gamal