I want to generate this query in sqlalchemy. The table 'demande' exists in the database. There is a subquery that generates the timesteps with the generate_series function.
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;
I've tried this :
stmt = session.query(
func.
generate_series(
datetime.datetime(2010,1,1,0,0,0),
datetime.datetime(2010,1,1,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
But it complains with an InvalidRequesError: Could not find a FROM clause to join from. I guess this is caused by the subquery.
If i try to "invert" the query, it works but it does a 'LEFT OUTER JOIN' :
q = session.query(
func.count(Demande.id),
stmt.c.timestep).
outerjoin((stmt, grouped==stmt.c.timestep)).
group_by(stmt.c.timestep)
As there is no RIGHT OUTER JOIN in sqlalchemy, I just want to find a way to take the subquery as the first table and the 'demande' table as the second one. This way I will be able to use LEFT OUTER JOIN
method sqlalchemy.orm.Query. all() Return the results represented by this Query as a list. This results in an execution of the underlying SQL statement. The Query object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will deduplicate entries based on primary key.
The following example should give you a clue (assuming I correctly guessed that Demande is declarative model):
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With