sqlsql-serverpivotdata-scrubbing

Pivot a table 4 rows at a time


I'm trying to figure out how to pivot a table in SQL Server in the following way:

enter image description here

Every time the value is "PEAK", I want it to start on a new row. Essentially it would look like this.

col1 col2 col3 col4 119 KH ON PEAK 4 K1 ON PEAK 356 KH OFF PEAK 38 K1 ... ...


Solution

  • Honestly, I'd really like to know how the source data is stored.. This seems like an awful lot of work when if the data is already stored in the correct rows splitting it there would be far easier...

    Roughly here's how I'd have to do it... All but the pivot is done...

    select bar, (row_number() over (order by a.b)-.001)/4 grpOrder,
    floor((row_number() over (order by a.b)-.001)/4) as grp
    from foo
    cross join (Select 1 as b) a
    

    Here's a screenshot from an oracle attempt I can't get SQL fiddle to work with SQL server right now.

    enter image description here

    From here you could pivot the data based on the decimal values of morder and each row would be based on grp.

    I had to use a cross join to get a value to order by but I needed it to be consistant so the order of the table foo would be preserved though this is by no means guaranteed. I would recommend adding an ID or sequence to your split data otherwise the order could get corrupted. If this is done we wouldn't need the cross join anymore. and the order by in the over order by could be set to that autonumber value.

    I'm assuming from here you could figure out how to pivot. as each decimal value value of MOrder will be the same within each group.

    and for the full pivot (again using oracle)

    enter image description here

    If your # of values in each group is dynamic, then we'd have to write some dynamic SQL to handle those situations; I've not done that here.