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

SQLAlchemy按小时分组时跨天同小时数据被合并的问题

问题原因

你的分组逻辑仅提取了时间中的小时维度,未携带日期信息:func.date_format(dlog.time, '%H')只会返回00-23的整数,不同日期的同一小时会被判定为同一个分组,所以跨天查询时最多只会返回24条统计结果。

解决方案

修改group_by的分组规则,同时按日期+小时两个维度分组即可:

resultset = DBSession.query(
    # 可选:替换原有dlog.time,返回规整的小时级时间标识
    func.date_format(dlog.time, '%Y-%m-%d %H:00:00').label("hour_time"),
    func.avg(dlog.value).label("value"),
    func.avg(dlog.minimum).label("minimum"),
    func.avg(dlog.maximum).label("maximum"))\
    .filter(dlog.time >= startObject, dlog.time <= endObject, dpoint.name == n)\
    # 分组时同时包含日期和小时
    .group_by(func.date_format(dlog.time, '%Y-%m-%d %H'))\
    .join(dpoint, dpoint.point_id==dlog.point_id)\
    .all()

如果使用的是PostgreSQL数据库,把date_format替换为to_char即可,格式参数规则一致。

内容的提问来源于stack exchange,提问作者Jesper

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 08:15:05