I have two queries. One that returns a count of records over the last 30 days, and another for the 30 days prior. I’d like to combine them into one query.
SELECT
cat.title as category, count(*) as total_count
FROM history h
JOIN users u on h.user_id = u.id
JOIN training t on t.id = h.app_id
JOIN training_categories tc on tc.training_id = t.id
JOIN category cat on cat.id = tc.category_id
WHERE u.department_id = 1 and h.type = 'virtual'
and h.app = 'training' and h.status = 'active'
and cat.status = 'active' and h.created_at >= (NOW() - INTERVAL '30 days')
GROUP BY cat.title
ORDER BY total_count DESC
SELECT
cat.title as category, count(*) as total_count
FROM history h
JOIN users u on h.user_id = u.id
JOIN training t on t.id = h.app_id
JOIN training_categories tc on tc.training_id = t.id
JOIN category cat on cat.id = tc.category_id
WHERE u.department_id = 1 and h.type = 'virtual'
and h.app = 'training' and h.status = 'active'
and cat.status = 'active' and h.created_at >= (NOW() - INTERVAL '60 days') and h.created_at < (NOW() - INTERVAL '30 days')
GROUP BY cat.title
ORDER BY total_count DESC
In my attempts to solve this so far it looks like I need a window function, but where I’m stuck is how to partition the query by 30-day increments.