[英]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我想要 select 列 VALUE 的最小值、最大值和平均值,其中时间戳 > 某个日期和 < 其他某个带有 LIMIT 和偏移量的日期
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.有人可能会认为
min
会用在select
语句中,而不用在 where 子句中。
Looking on the inte.net people are using all kind of different ways with sessions and ORMs and raw queries with filers etc.在 inte.net 上,人们正在使用各种不同的方式处理会话和 ORM,以及使用文件管理器等进行原始查询。
How do I create it with the above example?如何使用上面的示例创建它?
The first parameter to Table.select is a where clause. Table.select的第一个参数是一个 where 子句。 You have passed an aggregate function, and since aggregate functions are not permitted in
WHERE
clauses in SQL you get an error.您已经传递了一个聚合 function,由于聚合函数在 SQL 的
WHERE
子句中是不允许的,您会得到一个错误。
As Ben suggests in their comment , you would be better to use sqlalchemy.select like this:正如Ben在他们的评论中所建议的那样,您最好像这样使用sqlalchemy.select :
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.