我有一个用户记录表,我希望在满足某些条件时查看平均值。条件列是一个 bool 值。 在 Postgresql 中,我可以轻松地转换它:
select id, avg(cond::INT) from table group by id;
但是在 SQLAlchemy 中我找不到任何等同于 ::INT
的东西。
我如何处理类型转换?
我有
orm_query(Table.id, func.avg(Table.cond))
当然会返回错误。
最佳答案
<expr>::<type>
是Postgresql specific syntax , CAST(<expr> AS <type>)
标准 SQL 等价物。在 SQLAlchemy 中,您可以使用多种方式生成类型转换表达式。在这种情况下,您可以简单地:
orm_query(Table.id, func.avg(Table.cond.cast(Integer)))
另一种选择是使用 cast()
构造。
关于python - SQLAlchemy 将 bool 列转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48519633/