I have the following setup:
TableA:
id=1, type=Air
id=2, type=Sea
id=3, type=Land
... This is a dynamic list, so more could be added
TableB:
id=42, tableA_Id=1, name=Falcon
id=43, tableA_Id=1, name=Pigeon
id=44, tableA_Id=2, name=Shark
id=45, tableA_Id=3, name=Bear
id=47, tableA_Id=3, name=Wolf
... This is a dynamic list, so more could be added
Desired Output:
SomeOtherTableHeader, Air, Sea, Land, SomeOtherTableHeader
----------------------------------------------------------
someOtherValue, Falcon, Shark, Bear, someOtherValue
someOtherValue, Falcon, Shark, Wolf, someOtherValue
someOtherValue, Pigeon, Shark, Bear, someOtherValue
someOtherValue, Pigeon, Shark, Wolf, someOtherValue
- Note that the TableA contents are now column headers
- Note that this query needs to generate a row for every combination of TableB values.
In other words, I am trying to read a list of TableA values and use them to represent column headers. I am trying to create rows based on the combination of values in TableB
Is something like this even possible to do in a query (without a stored procedure)? If so, what would be the best/easiest way to achieve something like this?
Thanks!
If the contents of tableA are dynamic, you cannot do this with a simple SQL query (since a query needs to have a static set of columns).
The usual approach is to write a stored procedure that generates your SQL statement on-the-fly; for simplicity, I’ve just used a PL/SQL block: