简体   繁体   中英

how to select min, max and average with sqlalchemy

I want to select the min, max and average value of the column VALUE and where the timestamp > some date and < some other date with LIMIT and offset

from sqlalchemy import func
...

engine = create_engine(URL)
metadata = MetaData()

my_table = Table(
    "my_table",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("value", Numeric()),
    Column("timestamp", DateTime(timezone=True)),
)

database = Database(DATABASE_URL)
metadata.create_all(engine)

query = my_table.select(func.min(my_table.c.value)).where(my_table.c.timestamp > some_date).where(my_table.c.timestamp < some_other_date).limit(100)
result = database.fetch_all(query=query)

But i get the following error:

aggregate functions are not allowed in WHERE

This is partially the generated query:

SELECT my_table.id, my_table.value, my_table.timestamp FROM my_table WHERE min(my_table.value)

One might think that the min would be used in the select statement and not in the where clause.

Looking on the inte.net people are using all kind of different ways with sessions and ORMs and raw queries with filers etc.

How do I create it with the above example?

The first parameter to Table.select is a where clause. You have passed an aggregate function, and since aggregate functions are not permitted in WHERE clauses in SQL you get an error.

As Ben suggests in their comment , you would be better to use sqlalchemy.select like this:

query = sqlalchemy.select(func.min(my_table.c.value)).where(my_table.c.timestamp > some_date).where(my_table.c.timestamp < some_other_date).limit(100)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM