Oracle
 sql >> Base de Dados >  >> RDS >> Oracle

Misturando Connect by, inner join e soma com Oracle


Algo assim funcionaria? Já tive casos semelhantes ao seu, e simplesmente removi a junção da consulta hierárquica e apliquei-a somente depois para evitar a perda de linhas.
SELECT TaskName, Sum(ts.hours) "TotalHours" 
FROM (
    SELECT replace(sys_connect_by_path(decode(level, 1, t.name), '~'), '~') As TaskName, t.id
    FROM tasks t
    START WITH PARENTOID=-1
    CONNECT BY PRIOR t.id = t.parent_id
    ) tasks
INNER JOIN timesheets ts ON tasks.id=ts.task_id
GROUP BY TaskName Having Sum(ts.hours) > 0 ORDER BY TaskName