I\'ve got a \'Task\' table with the following columns (the TaskOrder is for ordering the children within the scope of the parent, not the entire table):
You don't need all that union stuff, I think this should work:
select
TaskId,
ParentTaskId,
[Name],
COALESCE(ParentTaskId, TaskId) as groupField
from
task
order by
COALESCE(ParentTaskId, TaskId), ParentTaskId, TaskId