Skip to content
Advertisement

Transform a table with duplicate unique id’s with different column values onto a single row

I am trying to transform the current format I have my data in 1 into the format of image 2. As you can see the data is currently split over two rows per one cust_id for each code they have but I want it on a single line. The open and replied for a given code is mutually exclusive for 1’s i.e. custx for code A does not have matching assigned values of 1 & 1 for open and replied but can have a 0 & 0, 1 & 0 or 0 & 1. I am using Oracle SQL Developer 19.2.1. Thank you in advance

Current SQL data format

enter image description here

Desired SQL data format

enter image description here

Advertisement

Answer

Try the following, here is the demo.

select
    cust_key,
    min(case when code = 'A' then open end) as A_open,
    min(case when code = 'B' then open end) as B_open,
    min(case when code = 'A' then replied end) as A_replied,
    min(case when code = 'B' then replied end) as B_replied
from yourTable
group by
    cust_key

Output:

|cust_key    A_open  B_open  A_replied  B_replied |
---------------------------------------------------
| cust1          0       0          1         0   |
| cust2          0       0          1         1   |
---------------------------------------------------
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement