-
Notifications
You must be signed in to change notification settings - Fork 80
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to implement a special top-N group function? #494
Comments
I think that the way you want the It is easy enough to write an aggregate function in PL/Java, the difficulty still remains in having a function that is simply called within a query somehow affect the If you wanted instead to write an CREATE OR REPLACE FUNCTION orders_topN(n integer)
RETURNS TABLE(product text, amount integer)
STABLE
BEGIN ATOMIC
SELECT product, total_amount
FROM (
SELECT product, sum(amount) AS total_amount
FROM orders
GROUP BY product
) AS q
ORDER BY total_amount*sign(n)
LIMIT abs(n);
END
(The reason for the nested If what you want is a function that takes n and the name of a column, that will aggregate just the named column, grouping by all the others, and applying an order and limit, that would be trickier. The caller would have to supply the name of the column (when you just use the column in the function call as your example does, only a value is passed, and the function doesn't know where it came from). The function would then have to generate appropriate SQL and execute it. If you wanted a function like that but polymorphic, so you could give it any table to operate on and have it return rows of that table's type (but grouped and with the named one aggregated), there might be a way to accomplish that, using PostgreSQL's support for polymorphic functions. It probably wouldn't be pretty, and might need a dummy argument of the table's row type. I'm not sure it would be worth the effort, except for the pure challenge of it. |
The table orders has some fields as following:
orderkey, product, amount, order_month, ......
I want to implement a UDF to use like:
select product, udf_topN(amount, -5) from orders group by product
this query means selecting the top 5 records by amount descending sort in each product group.
Can I implement this function using PL/Java and how to do? Please tell me where I can find such documents or information.
The text was updated successfully, but these errors were encountered: