irshan syed
irshan syed

Reputation: 89

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

Upvotes: 1

Views: 114

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269503

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.

Upvotes: 2

Mohammad
Mohammad

Reputation: 1990

You can use PIVOT statement like this to get intended result:

SELECT * FROM
(SELECT RowNumber, ID, Type FROM <Your Table Name>) source
PIVOT
(
    MIN (Value)
    FOR Category in 'Address', 'City', 'State', 'Zip'
) AS pvt

For more information see PIVOT documentation: https://learn.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017

Upvotes: 1

Related Questions