I have this working static query:
SELECT
companyname,
companyid,
incorporationcountryid,
periodEndDate,
filingdate,
AVG(dataitemvalue) FILTER (WHERE menmonic = 'AT') as "AT",
AVG(dataitemvalue) FILTER (WHERE menmonic = 'COGS') as "COGS"
FROM
aaa3
GROUP BY
companyname, companyid,
incorporationcountryid, periodEndDate, filingdate
ORDER BY
companyname, periodEndDate
Now, I’d like to incorporate all mnemonics, not just ‘AT’ and ‘COGS’ and adjust my query dynamically. I’m relatively new to SQL, but I managed to come up with this query, that gets me all unique mnemonics in my table and creates my desired query as a string:
SELECT 'SELECT companyname,companyid,incorporationcountryid,periodEndDate,filingdate,'
|| STRING_AGG(DISTINCT CONCAT('AVG(dataitemvalue) FILTER (WHERE menmonic = "', menmonic,'") as "',menmonic,'"'),',')
|| ' FROM aaa3 GROUP BY companyname, companyid, incorporationcountryid, periodEndDate, filingdate ORDER BY companyname, periodEndDate;'
as menmonic FROM aaa2;
Q: Can I turn this string into a query?
2
Answers
I was able to come up with a compact solution myself:
The first idea that comes up in mind would be to store your string into a text variable and then execute it as a dynamic query using
EXECUTE
(see the manual).But then comes the issue : the query to be executed has a variable number of columns depending on the number of menmonics in table aaa2.
So the problem is a bit more tricky and one possible solution is to create dynamically a composite type
menmonic_list
corresponding to the list of menmonics and then to use thejsonb_populate_record
andjsonb_object_agg
standard functions :Creating the composite type
menmonic_list
by trigger each time a row is inserted or updated or deleted from table aaa2 :The final query is :
see the test result in dbfiddle