Skip to content
Advertisement

Repeat column values in existing rows

Have a table with the following structure:

Rownumber ID     Type             Category Value
1         100   1-Purchase Order  Address  Cedar Rd
2                                 City     Beachwood
3                                 State    Ohio
4                                 Zip      44122
5         200   1-Purchase Order  Address  Rockside Rd
6                                 City     Independence
7                                 State    Ohio
8                                 Zip      44131

I would like to be able to pivot the table to move the Address, City, State and Zip values into columns. But for that to happen I guess I need the ID and Type to be populated for every record. Any guidance is appreciated.

Thank you

I added the rownumber field and thought about using LAG and LEAD but that did not work.

Desired Output
Rownumber  ID       Type            Category     Value
1          100   1-Purchase Order   Address     Cedar Rd
2          100   1-Purchase Order   City     Beachwood
3          100   1-Purchase Order   State    Ohio
4          100   1-Purchase Order   Zip      44122
5          200   1-Purchase Order   Address  Rockside Rd   
6          200   1-Purchase Order   City     Independence
7          200   1-Purchase Order   State    Ohio
8          200   1-Purchase Order   Zip      44131

And then eventually

Rownumber  ID   Type              Address      City        State  Zip
1         100  1-Purchase Order  Cedar Rd      Beachwood   Ohio   44122
2         200   1-Purchase Order Rockside Rd  Independence Ohio   44122

Advertisement

Answer

If I understand correctly, you can assign the id using a cumulative max and then use conditional aggregation:

select row_number() over (order by min(id)) as rownumber,
       new_id as id,
       max(type) as type,
       max(case when category = 'Address' then value end) as address,
       max(case when category = 'City' then value end) as city,
       max(case when category = 'State' then value end) as state,
       max(case when category = 'Zip' then value end) as zip
from (select t.*,
             coalesce(id, max(id) over (order by rownumber)) as new_id
      from t
     ) t
group by new_id;

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement