使用SQLAlchemy,PGSQL远程窗口子查询怎么做?

时间:2015-07-20 23:03:03

标签: python postgresql sqlalchemy window range

我的查询类似于以下内容:

  SELECT id, max(subq.foo), sum(subq.bar), etc...
  FROM (
      SELECT id,
           first_value(foo) over w as foo,
           etc...
      FROM my_table
      WHERE <where information>
      WINDOW w AS (PARTITION BY id 
                   ORDER BY time_stamp ASC
                   RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
  ) as subq

如何使用sqlalchemy完成此操作?特别是,我的问题是关于在内部查询上完成该窗口。

谢谢!

1 个答案:

答案 0 :(得分:1)

结束这样做:

# hack to get window supported
subq = subq.filter(text("TRUE WINDOW w AS (PARTITION BY id "
                        "ORDER BY time_stamp ASC "
                        "RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)"))

这将是应用于查询的最后一个过滤器,因此最终会得到这样的sql:

WHERE .... AND TRUE WINDOW w as (PARTITION BY id ORDER BY ...)