Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL sort records based on condition in many to many relation
    primarykey
    data
    text
    <p>I am unable to write SQL to sort records based on condition in many to many relationship. I have table structure <code>tasks</code> with many to many table for task dependencies. E.g. Task C can have one or many dependencies on other tasks trough table <code>task_dependencies</code>. </p> <ul> <li>TASKS: id, user_id, status_id, date_due, ...</li> <li>TASK_DEPENDENCIES: task_id, dependency_task_id (pivot table)</li> <li>Statuses are following: Q-new, G-In progress, L-closed</li> </ul> <p>The idea with task dependencies is that one task can not be started until all his dependency task(s) are closed. I would like to select all user's open tasks. This is easy. But I need to sort them by date_due, but having all the task with dependencies that can not be started yet on the end of result set. Meaning I need to somehow check if all dependency tasks are closed and take this into account when sorting somehow?</p> <p>I managed to put together one select but this always puts all tasks with dependencies at the end of the record set. But I would like to put tasks with closed dependencies in normal date_due order flow... </p> <pre><code>SELECT T.id, T.description, TD.dependency_task_id, ISNULL(TD.dependency_task_id) AS NoDependency, T.date_due FROM tasks T LEFT OUTER JOIN task_dependencies TD ON T.id = TD.task_id WHERE assigned_user_id=1 ORDER BY NoDependency DESC, T.date_due </code></pre> <p>Here is the SQL fiddle: <a href="http://sqlfiddle.com/#!2/894f7/3" rel="nofollow">http://sqlfiddle.com/#!2/894f7/3</a>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload