python - group_by 语句、sqlalchemy 和 postgresql 的问题

标签 python postgresql sqlalchemy

我对以下查询有疑问;这本身工作正常,但它按秒分组,我想截断秒并按分钟分组。我已经尝试过 date_trunc、extract 等,但我没有任何运气。当引擎是 sqlite 时,extract('minute') 工作正常,但不适用于 postgresql。

谁能给我指出正确的方向?

PostgreSQL 版本:x86_64-redhat-linux-gnu 上的 PostgreSQL 8.1.23

Column('id', Integer, primary_key=True),
        Column('date', TIMESTAMP),
        Column('src', String),
        Column('dst', String),
        Column('len', String),
        Column('sport', String),
        Column('dport', String),
        Column('method', String),
        Column('host', String),
        Column('useragent', String),
        Column('statusline', String),
        Column('location', String),
        Column('server', String),
        Column('load', String),

now = datetime.datetime.now()                
DD = now - datetime.timedelta(minutes=60)    
DD = DD.strftime('%Y-%m-%d %H:%M:%S')        
query = session.query(HTTP.date,HTTP.statusline, func.count(HTTP.statusline).                                                                           
                label('count')).filter(HTTP.statusline.like('%'+status+'%'), HTTP.date>=(DD)).group_by(HTTP.date, HTTP.statusline).order_by(asc(HTTP.date)).all()

最佳答案

在您做任何之前,请考虑升级到当前版本的 PostgreSQL 8.1 is long dead and forgotten .

不完全确定符号,但有来自 @Audrius in the comments 的更新它应该像这样工作:

query = session.query(
       date_trunc('min', http.date).label('date_minute')
      ,http.statusline
      ,func.count(http.statusline).label('count')
   ).filter(http.statusline.contains(status)
           ,http.date>=(DD)
   ).group_by('date_minute'
             ,http.statusline
   ).order_by(asc('date_minute')).all()

基本上,在 SELECT 中使用 date_trunc('min', http.date) 而不是 http.date ,在 中使用别名>GROUP BYORDER BY

顺便说一句:我发现使用 date 作为 timestamp 的名称非常具有误导性。除此之外,我的建议是永远不要使用任何基本类型名称作为标识符。导致非常困惑的错误消息和其他难以调试的错误。

关于python - group_by 语句、sqlalchemy 和 postgresql 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15866273/

相关文章:

python - 使用 'bokeh serve' (bokeh 0.12.0) 动态添加/删除绘图

sql - 使用 sql 连接的高效广度优先搜索

postgresql - 如何防止用户两次提款?

object - flask SqlAlchemy : TypeError: 'Class' object is not iterable

python - 有没有办法在 SQLAlchemy 连接字符串中指定 Postgres 模式?

python - .py 脚本直接进入 PyCharm

python - 套接字python中的异常列表

python - Odoo 11.0 使字段独一无二

postgresql - DBeaver,从数据库 Postgres 导出,表结构(属性)到文件 .txt

python - 如何通过代码使用 Python Alembic 运行迁移?