Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Conditional column data return in a select statement

Tags:

sql

Here is a simplication of the problem: I have a select that looks like this:

Select ID, Assignee, WorkStream from assignees; 

And a snap shot of the data returned looked like this

1|Joe Soap|Internal  2|Mrs Balls|External 

What I would like to do is have the select not display the Assignee name if the worksteam is internal. Instead to display the Workstream.

So for example the outcome I want to achieve would be this:

1|Internal|Internal  2|Mrs Balls|External 

I hope this makes sense? Basically a conditional select that can detect if a certain column contains a certain value, then replace another columns value with [whatever].

Thanks in advance!

EDIT I want to achieve something like this:

Select ID, if (workstream='internal' select Workstream as Assignee - else - select Assignee as Assigneee), WorkStream from assignees; 
like image 595
JL. Avatar asked Feb 15 '12 09:02

JL.


People also ask

How do I select a column based on a condition in SQL?

Solution 1. DECLARE @query VARCHAR(1000)=null; SET @query = 'ID'; IF((select phone1 from tablename where id = 1459) > 0) SET @query += ',phone1'; IF((select phone2 from tablename where id = 1459) > 0) SET @query += ',phone2'; .. .. .. IF (@query IS NOT NULL) exec('SELECT '+@query+' FROM tablename WHERE id = 1459');

Can we use select statement in if condition in SQL?

It is like a Shorthand form of CASE statement. We can conveniently use it when we need to decide between two options. There are three parts in IIF statement, first is a condition, second is a value if the condition is true and the last part is a value if the condition is false.


2 Answers

You didn't mention your DBMS but a searched CASE statement works in all major DBMS's I know off.

SELECT  ID         , CASE WHEN WorkStream = 'Internal'                THEN WorkStream                ELSE Assignee           END AS Assignee         , Workstream FROM    assignees 

Reference: MSDN

CASE

Evaluates a list of conditions and returns one of multiple possible result expressions.

like image 161
Lieven Keersmaekers Avatar answered Sep 19 '22 15:09

Lieven Keersmaekers


SELECT ID,         CASE WorkStream  WHEN 'Internal' THEN 'INTERNAL' ELSE Assignee as Assignee,    WorkStream  from assignees 

I hope this help.

like image 31
Pongsathon.keng Avatar answered Sep 20 '22 15:09

Pongsathon.keng