【问题标题】:How to join to generate_series with SQLAlchemy如何使用 SQLAlchemy 加入 generate_series
【发布时间】:2020-03-09 21:37:58
【问题描述】:

我正在尝试按月分类一些事件。

date_list = func.generate_series(start, end, '1 month')

db.session.query(func.count(Event.id)).join(date_list, true()).outerjoin(Event, Event.time==func.date(date_list)).all()

但我收到一个错误:

NotSupportedError: (psycopg2.errors.FeatureNotSupported) 在 JOIN 条件中不允许使用 set-returning 函数

使用 SQLAlchemy 在连接左侧使用系列,然后使用类似计数的聚合的简单示例是什么?

【问题讨论】:

    标签: python postgresql sqlalchemy


    【解决方案1】:

    我想知道您是否使用了this 作为参考,而忘记使用FunctionElement.alias()generate_series() 函数表达式中生成一个可选择项。现在您正在传递集合返回函数表达式,就像 ON 子句谓词的右侧一样。而是使用column() 来引用系列中的日期。使用 Query.select_from() 控制连接的左侧:

    from sqlalchemy import func, column
    
    start = ...
    end = ...
    date_list = func.generate_series(start, end, '1 month').alias('month')
    month = column('month')
    
    db.session.query(month, func.count(Event.id)).\
        select_from(date_list).\
        outerjoin(Event, func.date_trunc('month', Event.time) == month).\
        group_by(month)
        all()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-11
      • 2021-08-01
      • 2018-11-23
      • 2021-12-17
      • 1970-01-01
      • 2020-11-24
      • 2018-03-08
      • 2011-12-09
      相关资源
      最近更新 更多