I have a table of tasks. They have a property called completed. I would like to figure out what proportion of tasks in a certain date range have been completed.
Here's a window of tasks I'd like to analyse:
SELECT * from tasks
WHERE created_at > CURRENT_DATE - INTERVAL '15 day'
AND created_at < CURRENT_DATE - INTERVAL '5 day'
The rather clumsy approach I have so far
It's embarassing that I can't think of a smarter approach than this but for now this is all I have:
-- Calculate completion rate: completed / total
-- completed tasks
SELECT (
SELECT COUNT(*) from tasks
WHERE created_at > CURRENT_DATE - INTERVAL '15 day'
AND created_at < CURRENT_DATE - INTERVAL '5 day'
AND completed = true
)
-- / total tasks
/ SELECT (
SELECT COUNT(*) from tasks
WHERE created_at > CURRENT_DATE - INTERVAL '15 day'
AND created_at < CURRENT_DATE - INTERVAL '5 day'
)
How would I DRY this query out? I read up on the principle of creating a temporary view but that seems to be overkill for what's needed.