1

I have a table in my database with four columns: ID, task_name, due_date, completed_date

I am trying to use a subquery as one of output columns. Here is the SQL, which works fine:

SELECT 

due_date AS date,
COUNT(id) AS tasks_due,
( SELECT COUNT(id) FROM task_data WHERE completed_date IS NOT NULL AND due_date = T.due_date ) as tasks_completed,

FROM task_data T

GROUP BY date
ORDER BY date

The issue I am having is trying getting translate this bit into a SQLAlchemy query due_date = T.due_date

UPDATE I've managed to work it out. Code below, for anyone who is interested.

completed_tasks = (db.session.query(
                    Task.due_date, db.func.count(Task.id).label('tasks_completed'))
                   .filter(Task.completed_date != None)
                   .group_by(Task.due_date).subquery()
                  )

task_query = (db.session.query(
                Task.due_date.label('date'),
                db.func.count(Task.id).label('tasks_due'),
                completed_tasks.c.tasks_completed.label('tasks_completed'))
            .outerjoin(completed_tasks, Task.due_date == completed_tasks.c.due_date)
            .group_by(Task.due_date, completed_tasks.c.tasks_completed)
            .order_by(Task.due_date)
             )
1

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.