A download is comprised of download-times, download-time id, and buno ID. Faults are comprised of fault-codes, download-time id, status, and type. A download can have many
If you want counts by faultcode, this seems like the simplest solution:
WITH fc(faultcode) AS (VALUES (1000,1100))
SELECT fc.faultcode, count(d.downloadtimeid) as faultcount
FROM fc
LEFT JOIN (fs_fault f ON f.faultcode = fc.faultcode
AND f.statusid IN(2, 4)
JOIN download_time d ON d.id = f.downloadtimeid
AND d.bunoid = 166501
AND d.downloadtime::date BETWEEN date '2011-04-11'
AND date '2011-05-01')
GROUP BY fc.faultcode
ORDER BY fc.faultcode
Note that I kept your conditions, where faults are not counted if they don't have the right statusid or bunoid. I was a bit afraid that the date selection might not have been doing what you thought, so I suggested an alternative. Even that might not do what you want if you're using TIMESTAMP WITHOUT TIME ZONE
, but that's another story. I also added an ORDER BY
clause, since you probably don't want the results in inconsistent order; without that clause it may or may not be in GROUP BY
sequence, and that might change without warning.