简体   繁体   中英

SQL (PostgreSQL) Pivot based on prefix in values

Hello guys (and girls),

I am trying to pivot some values based on a prefix (yes_) in the values of another column to counteract duplications in my master_id.

Original table:

在此处输入图像描述

Preferred outcome:

在此处输入图像描述

Thanks in advance!

Maybe you can do it using pure sql

select
  t.master_id,
  max(case when t.col1 like 'yes%' then t.id else tt.id end) as id_yes,
  max(case when t.col1 not like 'yes%' then t.id else tt.id end) as id_no,
  max(case when t.col1 like 'yes%' then t.col1 else tt.col1 end) as col1_yes,
  max(case when t.col1 not like 'yes%' then t.col1 else tt.col1 end) as col1_no,
  max(case when t.col1 like 'yes%' then t.another_value else tt.another_value end) as another_value_yes  
  max(case when t.col1 not like 'yes%' then t.another_value else tt.another_value end) as another_value_no
from your_table t
  left join your_table tt
    on t.master_id = tt.master_id
   and t.id <> tt.id
group by t.master_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM