-- This is the first part of the query to get a list of skycells with
-- warps to be stacked, along with the number of warps already in a
-- stack.  It needs to be completed by part 2 (see below).

SELECT
    skycell_id,
    filter,
    tess_id,
    num_warp,
    MAX(num_stack) AS num_stack
FROM ((
    -- Number of stack-ready warps as a function of skycell and filter
    SELECT
        skycell_id,
        warpSkyfile.tess_id as tess_id,
        rawExp.filter,
        COUNT(warpSkyfile.skycell_id) AS num_warp -- number of warps that can be stacked
    FROM warpRun
    JOIN warpSkyfile USING(warp_id)
    JOIN fakeRun USING(fake_id)
    JOIN camRun USING(cam_id)
    JOIN chipRun USING(chip_id)
    JOIN rawExp USING(exp_id)
    WHERE
        warpRun.state = 'full'
        AND warpSkyfile.fault = 0
        AND warpSkyfile.quality = 0
    -- Here should follow the SQL in stacktool_definebyquery_part2.sql,
    -- after any additional WHERE conditions have been added

