【问题标题】:Sqlalchemy; count items between two dates over a time period炼金术;计算一段时间内两个日期之间的项目
【发布时间】:2022-09-27 11:25:13
【问题描述】:

我的 postgres 数据库有一个价格表,我在其中存储了一堆产品的价格数据。对于我在创建时存储的每个 Price 对象(Price.timestamp),每当产品有新价格时,我都会创建一个新的 Price 对象,并在结束时存储旧的 Price 对象(Price.end_time) .这两个时间都是日期时间对象。

现在,我想计算一段时间内有多少价格。我想很容易,所以我做了以下查询:

trunc_date = db.func.date_trunc(\'day\', Price.timestamp)

query = db.session.query(trunc_date, db.func.count(Price.id))
query = query.order_by(trunc_date.desc())
query = query.group_by(trunc_date)
prices_count = query.all()

这很好,但只计算每天新/创建的价格。所以我认为我可以做的是过滤,以便获得 trunc_date 介于价格开始和结束之间的价格,如下所示:

query = query.filter(Price.timestamp < trunc_date < Price.time_ended)

但显然你不允许以这种方式使用 trunc_date 。任何人都可以帮助我如何编写查询吗?

    标签: postgresql flask sqlalchemy


    【解决方案1】:

    您是否尝试过分离过滤器内的条件?

    query = db.session.\
        query(trunc_date, db.func.count(Price.id)).\
        filter(
            (Price.timestamp < trunc_date),
            (trunc_date < Price.time_ended)
            ).\
        group_by(trunc_date).\
        order_by(trunc_date.desc()).\
        all()
           
    

    【讨论】:

      猜你喜欢
      • 2021-01-23
      • 2012-01-31
      • 2020-05-15
      • 2017-10-29
      • 2010-09-17
      • 2021-11-20
      • 2012-02-13
      • 2021-11-25
      • 2011-08-01
      相关资源
      最近更新 更多