Skip to content
Advertisement

SQL – create new col based on value of other column group by third column

I have this table

Id item type
A itemA1 X
A itemA2 X
B itemA1 X
B itemA2 X
B itemA3 Y

And i would like to create new indicator which contains the information about if the Id contains only item of type X or only tpye Y or both like this :

Id Indicator
A Only X
B Both

EDIT: It’s possible to have more than 2 kind of types

Thanks in advance for your help

Advertisement

Answer

Consider below generic approach

select id, 
  if(count(distinct type)=1,'Only ','') || string_agg(distinct type) indicator
from your_table
group by id
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement