Skip to content
Advertisement

SQL frame a result table from a table by searching its field

I have a table as below.

MyTabl

Name    Main    Group3

Xyz     Group2  Group3
ABC     Group1  Group3
PQR     -       Group3

I need to frame the result table with the fields. “Name”, “IsGroup1”, “IsGroup2” and “IsGroup3”.

I am trying to frame the query like below,

    select Name, 
if(Main = "Group1") return 1 as IsGroup1,  
if(Main = "Group2") return 1 as IsGroup2,  
if(Group3= "Group3") return 1 as IsGroup3
    from myTable

Please give me some suggestion on How I can get results like this.

Advertisement

Answer

Use case:

select name,
       (case when main = 'Group1' then 1 else 0 end) as isgroup1,
       (case when main = 'Group2' then 1 else 0 end) as isgroup2,
       (case when main = 'Group3' then 1 else 0 end) as isgroup3
from mytable;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement