I am trying to create a stored procedure in Sybase
Adaptive Server Anywhere
that will do a double pivot of table. I will first outline with some images what I am trying to accomplish.
The problem
- Raw data
Here is the raw data in the table; in the sample code that I have posted lower down this is temporary table #t1 :
- First level of pivoting
The first level of pivoting involves grouping on the column rownr
and pivoting on the column col
, putting the resulting table into temporary table #t2 :
I have the code up to this point which I have posted lower down.
- Second level of pivoting
This is the section that I am struggling with. I am now needing to pivot table #t2 grouping on the column ObjectId
and replicating the columns Operation
and Code
for the number of rows in the grouping to produce table #t3. So the result for the example I have given would look like this:
Because two columns are being replicated (Operation
and Code
) the number of columns in the resulting table should equal 2 multiplied by the number of rows in the grouping with the largest number of rows. Groupings that have less than the maximum number of grouped rows will be padded with null values, as seen in the example.
The code
Here is my code that creates the first two tables, #t1 and #t2 :
begin
create table #t1(rownr int, col nvarchar(15), val nvarchar(300));
insert into #t1 values(1, 'ObjectId', 'A');
insert into #t1 values(1, 'Operation', 'Op1');
insert into #t1 values(1, 'Code', '101');
insert into #t1 values(2, 'ObjectId', 'A');
insert into #t1 values(2, 'Operation', 'Op2');
insert into #t1 values(2, 'Code', '102');
insert into #t1 values(3, 'ObjectId', 'B');
insert into #t1 values(3, 'Operation', 'Op3');
insert into #t1 values(3, 'Code', '103');
insert into #t1 values(4, 'ObjectId', 'B');
insert into #t1 values(4, 'Operation', 'Op4');
insert into #t1 values(4, 'Code', '104');
insert into #t1 values(5, 'ObjectId', 'B');
insert into #t1 values(5, 'Operation', 'Op5');
insert into #t1 values(5, 'Code', '105');
-- Create t2
select
rownr,
Max(case when col = 'ObjectId' then val end) as ObjectId,
Max(case when col = 'Operation' then val end) as Operation,
Max(case when col = 'Code' then val end) as Code
into #t2
from #t1
group by rownr
order by rownr, ObjectId;
select * from #t2;
-- Create #t3 <--- This is where I need help
end
Take note
Please note that I am trying to solve this for Sybase
Adaptive Server Anywhere
which does not have a pivot
statement like Sql Server
does, so a solution using a pivot
statement will not help me.