Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Statement - Only when condition

Tags:

sql

sql-server

Take a look in the table below:

Status ----------------- Email
Approved [email protected] 
Canceled --------------- [email protected] 
Canceled --------------- [email protected] 
Canceled --------------- [email protected] 
Canceled --------------- [email protected] 

I execute the query

"SELECT DISTINCT Status, Email FROM dbo.sales":

Status ----------------- Email
Approved --------------- [email protected] 
Canceled [email protected] 
Canceled --------------- [email protected] 

I'd like to set up a query to select the rows that have the status "Canceled" ONLY WHEN there is not a row with the same email with the status "Approved".

In other words, I'd to select only the last entry (Canceled - [email protected]) in this example.

Is it possible? Thanks in advance.

like image 720
user3367290 Avatar asked Mar 01 '14 04:03

user3367290


People also ask

How do you write a conditional SELECT statement in SQL?

IF(condition, True, False) from table; An IF statement simple introduces some condition and then returns a result based on whether the condition is true or false.

Can we write SQL query in if condition?

We can use SQL IF statement without ELSE as well. In the following, the expression evaluates to TRUE; therefore, it prints the message. If the expression evaluates to FALSE, it does not return any output. We should use ELSE statement so that if an evaluation is not TRUE, we can set default output.

What is SQL IIF?

IIF is a shorthand way for writing a CASE expression. It evaluates the Boolean expression passed as the first argument, and then returns either of the other two arguments based on the result of the evaluation.


1 Answers

Select distinct status,email
From dbo.sales
Where email Not In ( select email from dbo.sales
                      Where status='Approved' )
like image 151
Mudassir Hasan Avatar answered Oct 22 '22 07:10

Mudassir Hasan