Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid duplicates with case statement

I have a table with the following structure (customer id and product):

my_table

I’m trying to pivot the same, in order to have just one line per Id.
To do this, I’m using case statements:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

select distinct
id,
case when purchased_item = 'Item 1' then 'Y' else 'N' end item_1,
case when purchased_item = 'Item 2' then 'Y' else 'N' end item_2,
case when purchased_item = 'Item 3' then 'Y' else 'N' end item_3
from my_table

However, this is the result I get:

query result

Is there any way to get the same result but with just one single line per Id?

>Solution :

to answer your problem , you need to group by and use max fucntion:

select 
  id,
  max(case when purchased_item = 'Item 1' then 1 else 0 end) item_1,
  max(case when purchased_item = 'Item 2' then 1 else 0 end) item_2,
  max(case when purchased_item = 'Item 3' then 1 else 0 end) item_3
from my_table
group by id
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading