如何在sqlalchemy中生成此查询?
发布时间:2020-12-13 18:10:40 所属栏目:百科 来源:网络整理
导读:我想在sqlalchemy中生成此查询.表’demande’存在于数据库中.有一个子查询使用generate_series函数生??成时间步长. SELECT timesteps.timestep AS timestep,d.count AS countFROM (SELECT DATE_TRUNC('hour',date_demande) AS timestep,COUNT(id) AS count F
我想在sqlalchemy中生成此查询.表’demande’存在于数据库中.有一个子查询使用generate_series函数生??成时间步长.
SELECT timesteps.timestep AS timestep,d.count AS count FROM (SELECT DATE_TRUNC('hour',date_demande) AS timestep,COUNT(id) AS count FROM demande GROUP BY timestep ) AS d RIGHT OUTER JOIN (SELECT timestep FROM generate_series('2010-01-01 00:00:00'::timestamp,'2010-01-01 23:59:59'::timestamp,'1 hour'::interval) AS timestep ) AS timesteps ON d.timestep = timesteps.timestep ORDER BY timestep; 我试过这个: stmt = session.query( func. generate_series( datetime.datetime(2010,1,0),datetime.datetime(2010,23,59,59),cast('1 hour',Interval())). label('timestep') ).subquery() print stmt q = session.query( stmt.c.timestep,func.count(Demande.id)). outerjoin((Demande,grouped==stmt.c.timestep)). group_by(stmt.c.timestep) print q 但它抱怨InvalidRequesError:无法找到要加入的FROM子句.我想这是由子查询引起的. 如果我试图“反转”查询,它可以工作,但它做’左外连接’: q = session.query( func.count(Demande.id),stmt.c.timestep). outerjoin((stmt,grouped==stmt.c.timestep)). group_by(stmt.c.timestep) 由于sqlalchemy中没有RIGHT OUTER JOIN,我只想找到一种方法将子查询作为第一个表,将’demande’表作为第二个表.这样我就可以使用LEFT OUTER JOIN了
下面的例子应该给你一个线索(假设我正确猜到Demande是声明性模型):
joined = stmt.outerjoin(Demande.__table__,Demande.grouped==stmt.c.timestep) q = session.query(stmt.c.timestep,func.count(Demande.id)). select_from(joined). group_by(stmt.c.timestep) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- 使用XML Schema来扩展元素而不是complexType
- ruby-on-rails – 我的非模型/非控制器代码应该在
- sqlite3 alter table
- [cocos2dx-lua]Cocos2dx-Lua中Sprite精灵的3种创
- 快速优雅的为React组件生成文档
- c – 我可以在Redhat Linux机器上使用在Ubuntu上
- c# – Resharper,“返回类型可以是IEnumerable …
- oracle – JetBrains的DataGrip是否支持PL / SQL
- 数组 – 如何在使用JSON.NET中的List属性进行序列
- iPhone SDK:用于停止加载/下载图像的UIWebView
热点阅读