My question is: How can I replace some complex calculation using custom defined functions in such way that the statements from the query who called the function affect the function output in postgres? I will give an example to clarify it a little bit more. Assume we have the following table:
CREATE TABLE test (my_id INT, cat_col VARCHAR(1), col1 INT, col2 INT);
INSERT INTO test
VALUES
(0, 'a', 1, 3),
(1, 'a', 4, 5),
(2, 'b', 2, 8),
(3, 'b', 3, 6);
Consider the following query:
SELECT cat_col, SUM(col1 * col2)
FROM test
WHERE my_id >= 1
GROUP BY cat_col;
Let's pretend the statement SUM(col1 * col2) is very complex and we cannot easily put it in the query just like we did, how can I write a function to replace this statement? Something like:
SELECT cat_col, f(params)
FROM test
WHERE my_id >= 1
GROUP BY cat_col;
I think there must be a way to pass the filtered and grouped column to the function, but I do not have two much experience with user defined functions and after reading the postgres documentation i could not come up with a solution yet. Can someone help me out?