I have a Denormalized Table (say TableA) with the following Columns:
TableA_Id
Cat1
Cat2
Cat3
Cat4
Cat5
Cat6
With entries like:
TableA_ID | Cat1 | Cat2 | Cat3 | Cat4 | Cat5 | Cat6
1 | 32 | 29 | NULL | NULL | NULL | NULL
2 | 30 | 56 | 89 | NULL | NULL | NULL
3 | 32 | NULL| NULL | NULL | NULL | NULL
4 | 55 | 65 | 32 | 69 | 3 | 9
I want to convert it into another Table (say TableB) with contains unique associations b/w TableA_ID and the Cat_IDs.
TableB structure
Assoc_Id serial,
TableA_ID int,
Cat_ID int;
And TableB will have association entries (from TableA) Like:
Assoc_Id | TableA_ID | Cat_ID
1 | 1 | 32
2 | 1 | 29
3 | 2 | 30
4 | 2 | 56
5 | 2 | 89
6 | 3 | 32
7 | 4 | 55
8 | 4 | 65
9 | 4 | 32
10 | 4 | 69
11 | 4 | 3
12 | 4 | 9
Can someone please help?
Thanks in advance.
Elegance is good, but sometimes simple brute force is sufficient. Esp. on what should be a 1 time, or very few executions.
insert into TableB (TableA_id, Cat_id)
select TableA_id, cat1 from tableA where cat1 is not null union all
select TableA_id, cat2 from tableA where cat2 is not null union all
select TableA_id, cat3 from tableA where cat3 is not null union all
select TableA_id, cat4 from tableA where cat4 is not null union all
select TableA_id, cat5 from tableA where cat5 is not null union all
select TableA_id, cat6 from tableA where cat6 is not null ;