markyoung
markyoung

Reputation: 179

Grouped IF statement in SQL

My data take this basic shape: (http://sqlfiddle.com/#!9/d4ae98/1)

CREATE TABLE Table1
(`ID` int, `Type` varchar(1));

INSERT INTO Table1
(`ID`, `Type`)
VALUES
(123, 'A'),
(123, 'B'),
(123, 'C'),
(456, 'A'),
(789, 'A'),
(789, 'B')
;

What I want is, a third column which is true/false for every row, based on whether that row's ID value has type='B' anywhere in the data. So the desired output would be:

ID   Type   V3
123  A      t
123  B      t
123  C      t
456  A      f
789  A      t
789  B      t

What is the best way to do this? (And, yes, I am aware that a scripting language like R or Python could easily do what I want here, but I want to use this output as a WITH clause in a larger SQL query.)

Upvotes: 0

Views: 40

Answers (2)

Mohamad TAGHLOBI
Mohamad TAGHLOBI

Reputation: 591

May a solution like this one can help you:

with Table2 as (
select * from table1 where type ='B'
)
select t1.*, case t2.type when 'B' then 't' else 'f' end v3 from table1 t1 left 
outer join table2 t2 on t1.id = t2.id ;

Upvotes: 0

eshi
eshi

Reputation: 71

You can do this with a Case in the Select:

select *, CASE
WHEN id in (select id from table1 where type like '%B%') then 't'
ELSE 'f'
END V3
from table1;

Fiddle link: http://sqlfiddle.com/#!9/e47bc37/1

Upvotes: 1

Related Questions