I'm trying create a Crosstab query to retrieve custom values from my database, and match them to a parent entity. I have the crosstab functioning, but the problem I have is that my results are entirely unknown.
To explain, my application features a Custom Field module, where users of the application can define their own fields. The values for these fields are then entered by the user. Of course, the custom fields have their own names that are defined by the users, and can be changed by those users on the fly. There's also no upper limit to the number of fields that they could create. As such, there's no way for me to have the final_result of the crosstab defined. It needs to be dynamic and created at the moment of the query, and I'm not sure how to accomplish this.
Here's my current crosstab query:
SELECT *
FROM CROSSTAB(
$$
SELECT A.AGREEMENTNUMBER, CFCM.NAME, CFV.VALUE
FROM AGREEMENTS A
LEFT JOIN CUSTOMFIELDVALUES CFV ON CFV.FK_AGREEMENT = A.ID
LEFT JOIN CUSTOMFIELDCONTRACTMETA CFCM ON CFCM.ID = CFV.FK_CUSTOMFIELDMETA
ORDER BY 1,2
$$,
$$
SELECT CFCM.NAME
FROM CUSTOMFIELDCONTRACTMETA CFCM
$$
) AS final_result(AGREEMENTNUMBER TEXT, TEST_TEXT TEXT, TEST_CURRENCY TEXT, TEST_LIST TEXT);
You can see that I currently have three custom fields prepared in my application (TEST_TEXT, TEST_CURRENCY, and TEST_LIST). The problem is that users would likely enter things like "Amount of money spent this quarter" or something like that. And the biggest problem is that these are entirely controlled by the users and I have no ability to predict what they will have. Is there any possible way to define my result of the crosstab utilizing a query? I'd essentially like to use the same query that I utilized for the Category_SQL. So, something akin to:
SELECT *
FROM CROSSTAB(
$$
SELECT A.AGREEMENTNUMBER, CFCM.NAME, CFV.VALUE
FROM AGREEMENTS A
LEFT JOIN CUSTOMFIELDVALUES CFV ON CFV.FK_AGREEMENT = A.ID
LEFT JOIN CUSTOMFIELDCONTRACTMETA CFCM ON CFCM.ID = CFV.FK_CUSTOMFIELDMETA
ORDER BY 1,2
$$,
$$
SELECT CFCM.NAME
FROM CUSTOMFIELDCONTRACTMETA CFCM
$$
) AS final_result(AGREEMENTNUMBER TEXT, SELECT CFCM.NAME FROM CUSTOMFIELDCONTRACTMETA CFCM);