[英]SQLAlchemy ORM How to Calculate Median With Query PERCENTILE_DISC WITHIN GROUP (ORDER BY {column})?
I am using SQLAlchemy 1.4 ORM with a Postgres database and can't find a way to use the ORM to calculate the median of a column.我正在使用 SQLAlchemy 1.4 ORM 和 Postgres 数据库,但找不到使用 ORM 计算列中位数的方法。
This is the SQL statement I want to replicate:这是我要复制的 SQL 语句:
select PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY ${column}) AS ${column}_median from ${table};
Here is an example of the output when querying the database directly with raw SQL:以下是使用原始 SQL 直接查询数据库时 output 的示例:
select PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY used) AS used_median from speed_limit;
used_median
--------------
18
(1 row)
In the SA docs this is suggested:在 SA文档中,建议这样做:
func.unnest(
func.percentile_disc([0.25,0.5,0.75,1]).within_group(user_table.c.name)
This does not meet my requirement as it not using the SA ORM.这不符合我的要求,因为它没有使用 SA ORM。
I have tried doing something like this in Python utilizing the ORM:我曾尝试使用 ORM 在 Python 中做这样的事情:
session.query(func.percentile_disc(0.5).within_group(SpeedLimit.used)).scalar()
This does not give the expected result 18
, it returns 8
.这没有给出预期的结果18
,它返回8
。
When I switch scalar
for all
like this:当我像这样为all
切换scalar
时:
session.query(func.percentile_disc(0.5).within_group(SpeedLimit.used)).all()
This doesn't return the correct response either, it returns [(8,)]
这也不返回正确的响应,它返回[(8,)]
I have not been able to find anything in the documentation about creating this query through the ORM.我无法在文档中找到有关通过 ORM 创建此查询的任何内容。
If anyone can point me in the right direction it would be appreciated: :)如果有人能指出我正确的方向,将不胜感激::)
I just realized I was using the wrong func
call!我刚刚意识到我使用了错误的func
调用!
The ORM query should read ORM 查询应为
session.query(func.percentile_cont(0.5).within_group(SpeedLimit.used)).scalar()
This gives the correct response.这给出了正确的响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.