pypika icon indicating copy to clipboard operation
pypika copied to clipboard

Recommended way to support "WITHIN GROUP"

Open lightupyiqian opened this issue 4 years ago • 3 comments

Hi, Is there a way to accomplish percentile_cont(fraction) WITHIN GROUP (ORDER BY sort_expression)? https://www.postgresql.org/docs/9.4/functions-aggregate.html

lightupyiqian avatar Nov 10 '20 00:11 lightupyiqian

Also interested in a similar thing: I have implemented some PostgreSQL specific AggregateFunction in our code, and I'd love to be able to pass ORDER BY sort_expression into them, ala JSONB_AGG("table_name" ORDER BY "table_name"."sort_expression")

I think in both cases we would like to extend the behavior of AggregateFunction to include some more inner expressions?

benjaminsanborn avatar Feb 12 '21 16:02 benjaminsanborn

Just to follow up; I extended AggregateFunction and implemented get_special_params_sql to add the appropriate keywords inside the function; as is done in AnalyticFunction.

benjaminsanborn avatar Feb 18 '21 17:02 benjaminsanborn

This was a total hack, but one way I got something working was to add it as a Field. That tended to give better rendered queries, than just putting in a plain string:

from pypika import Table, Query, Field

table = Table('tablename')
q = Query\
    .from_(table)\
    .select(
        Field('percentile_cont(0.1) within group (order by column asc) as col_perc')
    )
q.get_sql()
'SELECT "percentile_cont(0.1) within group (order by column asc) as col_perc" FROM "tablename"'

Again, this was a hack, use it at your own risk! It would be better to have an actual WithinGroup implementation in pypika, but this at least got me an answer.

mccarthyryanc avatar Oct 25 '21 16:10 mccarthyryanc