SELECT
    staticskyRun.sky_id,
    staticskyRun.workdir,
    staticskyRun.reduction,
    staticskyRun.label,
    staticskyRun.state,
    stackRun.tess_id,
    stackRun.skycell_id,
    IFNULL(Label.priority, 10000) AS priority
FROM staticskyRun
JOIN staticskyInput USING (sky_id)
JOIN stackRun USING (stack_id)
LEFT JOIN staticskyResult USING(sky_id)
LEFT JOIN Label ON staticskyRun.label = Label.label
WHERE
   (staticskyRun.state = 'new' AND staticskyResult.sky_id IS NULL)
   AND (Label.active OR Label.active IS NULL)

    -- WHERE hook %s
GROUP BY sky_id
HAVING SUM(IF(stackRun.state = 'full', 1, 0)) = COUNT(staticskyInput.sky_id)
ORDER BY priority DESC, sky_id
