I have a table structured as follows:
CREATE TABLE t (
HHID varchar2(1),
INDIV_ID int,
PRIM varchar2(1)
);
insert into t values ('A', 10, 'Y');
insert into t values ('A', 11, 'N');
insert into t values ('A', 12, 'N');
insert into t values ('A', 13, 'N');
insert into t values ('B', 14, 'N');
insert into t values ('B', 15, 'Y');
insert into t values ('C', 16, 'Y');
insert into t values ('C', 17, 'N');
What I need is to convert this to the following:
HHID PRIMARY SECOND THIRD FOURTH FIFTH ....
A 10 11 12 13
B 15 14
C 16 17
Big issue is that the number of possible added columns is unknown, I just need the primary INDIV_ID to show up as the primary and any additionals to be capture in subsequent columns.
Every answer I've looked at right now only suggests answers for the case for a simple pivot of a row id to the column ID however, I haven't seen a pivot that manages to place subsequent records of the same HHID as an additional column.
Best Answer
To get the primary value first, then the values by indiv_id, assign each row a number starting at 1 for each hhid:
Once you've got that, you pivot by the values 1, 2, 3, ..., N.
If you know (or can make a reasonable guess...) as to the max number of rows/hhid you're done. If you want the columns in the output to change, there's no simple solution.
You could XML pivot:
But that's kinda cheating as you still have one column. And you need to parse the XML...
Or you can fall back on dynamic SQL: