0

I am trying to write a query in Peewee with a PostgreSQL backend to return the top product exported by each state based on the export_value for a given product-state pair. Here is the query I have right now:

    subquery = (
        models.Trade.select(
            models.Trade.state.alias('state_1'),
            models.Trade.product.alias('product_1'),
            fn.SUM(models.Trade.export_value).alias("export_value_1")
        ).where(
            models.Trade.origin_country == origin_country,
            models.Trade.year == year
        ).group_by(
            models.Trade.state,
            models.Trade.product
        ).alias("subquery")
    )

    query = (
        models.Trade.select(
            models.Trade.state,
            models.Trade.product,
            fn.MAX(subquery.c.export_value_1).alias("export_value")
        ).join(
            subquery, on=(
                (models.Trade.state == subquery.c.state_1) &
                (models.Trade.product == subquery.c.product_1)
            )
        ).group_by(
            models.Trade.state
        )
    )

I am getting an error running this query because I am not using the models.Trade.product in a GROUP BY or aggregator. I am new to Peewee and would like any tips on how I can accomplish what I want either by modifying this query or through a different query.

MarcioPorto
  • 555
  • 7
  • 22
  • 1
    I don't know these frameworks, but the error message is clear, and a very common mistake made by beginners. You are doing `GROUP BY` certain columns, which means you may _only_ select those columns, or select an aggregate function of any column. Check the raw SQL and you will see the error immediately. – Tim Biegeleisen May 24 '18 at 05:33
  • Thanks Tim! But if I add that column to the `GROUP BY` then I don't get the results I want and I need to select that column. Is there a way to keep the column and still get the results I want? Or maybe another better way to design this query? – MarcioPorto May 24 '18 at 05:45
  • 1
    You hit the spot with "better way to design this query." This isn't really a Peewee/Flask problem at all, it's a SQL question. So, you should have posted your raw SQL query instead of so much code. – Tim Biegeleisen May 24 '18 at 05:46
  • I don't think you need a group by on the outer query. – coleifer May 25 '18 at 17:51

0 Answers0