The Question:
I have a view that is a list of fields in tables:
FIELD_LIST_VW
+-------------+------------+
| TABLE_NAME | FIELD_NAME |
+-------------+------------+
| ENG.TABLE_1 | FIELD_1 |
| ENG.TABLE_1 | FIELD_2 |
| ENG.TABLE_2 | FIELD_A |
+-------------+------------+
The underlying tables look like this:
TABLE_1
+---------+---------+
| FIELD_1 | FIELD_2 |
+---------+---------+
| A | X |
| A | Y |
| B | Y |
| B | Y |
| B | |
| C | |
+---------+---------+
TABLE_2
+---------+
| FIELD_A |
+---------+
| 1 |
| 1 |
| 1 |
| 2 |
| 3 |
+---------+
TABLE_3, TABLE_4, etc...
I want to expand the list of fields from FIELD_LIST_VW
, so that there is a row for each unique value, per field:
+-------------+------------+--------------+
| TABLE_NAME | FIELD_NAME | UNIQUE_VALUE |
+-------------+------------+--------------+
| ENG.TABLE_1 | FIELD_1 | A |
| ENG.TABLE_1 | FIELD_1 | B |
| ENG.TABLE_1 | FIELD_1 | C |
+-------------+------------+--------------+
| ENG.TABLE_1 | FIELD_2 | X |
| ENG.TABLE_1 | FIELD_2 | Y |
+-------------+------------+--------------+
| ENG.TABLE_2 | FIELD_A | 1 |
| ENG.TABLE_2 | FIELD_A | 2 |
| ENG.TABLE_2 | FIELD_A | 3 |
+-------------+------------+--------------+
What I've tried:
I figure a good place to start would be a cross join
sub-select:
SELECT
a.table_name
,a.field_name
,b.unique_value
FROM
eng.field_list_vw a
CROSS JOIN (
SELECT
'FIELD_1' AS field_name --<-- Hardcoded
,field_1 AS unique_value --<-- Hardcoded
FROM
eng.table_1 --<-- Hardcoded
GROUP BY
field_1 --<-- Hardcoded
) b
WHERE a.field_name = b.field_name
But of course, the cross join
sub-select is full of hardcoded table & field names. The query joins TABLE_1
, FIELD_1
, but not any of the other fields in FIELD_LIST_VW
. This is not what I want:
+-------------+------------+--------------+
| TABLE_NAME | FIELD_NAME | UNIQUE_VALUE |
+-------------+------------+--------------+
| ENG.TABLE_1 | FIELD_1 | A |
| ENG.TABLE_1 | FIELD_1 | B |
| ENG.TABLE_1 | FIELD_1 | C |
+-------------+------------+--------------+
(rows are missing)
Instead of hardcoding, is there a way to dynamically cross join to the unique values of each field in FIELD_LIST_VW
?
I do not have CREATE TYPE
privileges.
FIELD_LIST_VW
). UsingUNION
, notCROSS JOIN
by the way.