You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQLAlchemy 2.0 ORM模式下统计结果行转换实现求助

解决方案

直接通过聚合函数在单条查询中计算所需的三个统计值,无需分组:

async with self.session_context() as session:
    query = select(
        # 总记录数
        func.count("*").label("count_total"),
        # replied为True的记录数
        func.sum(
            case(
                (db_model.Review.replied == True, 1),
                else_=0
            )
        ).label("count_true"),
        # 计算占比,用nullif避免除以0报错
        (
            func.sum(
                case(
                    (db_model.Review.replied == True, 1),
                    else_=0
                )
            ) / func.nullif(func.count("*"), 0)
        ).label("share")
    ).where(db_model.Review.location_id == location_id)
    
    result = await session.execute(query)
    # 获取单行统计结果,返回Row对象,可通过属性访问值
    stats_row = result.scalar_one()
    # 示例取值:stats_row.count_total, stats_row.count_true, stats_row.share

关键说明

  • func.count("*"):直接统计符合location_id条件的所有记录数,对应你要的total。
  • func.sum(case(...)):通过case表达式将replied=True的记录标记为1,其余为0,求和后得到replied的数量。
  • func.nullif(func.count("*"), 0):当总记录数为0时,将分母转为NULL,避免除法报错,你也可以根据需求改成返回0。

内容的提问来源于stack exchange,提问作者loki.dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 05:40:05