I'm building a MySQL query to determine how many items from each of several categories appear in a given date range. My initial attempt looked like this:
select Title,
(select count(*) from entries where CategoryID=1
and Date >= @StartDate and Date <= @EndDate) as Cat1,
(select count(*) from entries where CategoryID=2
and Date >= @StartDate and Date <= @EndDate) as Cat2,
(select count(*) from entries where CategoryID is null
and Date >= @StartDate and Date <= @EndDate) as UnkownCategory
from entries
where Date >= @StartDate and Date <= @EndDate
The table is quite large and I'd like to refactor the query to speed it up, but I'm not sure how - can this be rewritten using GROUP BY/HAVING statements or is there another way I'm missing?
Edit: Sample result set - something like this:
Title | Category 1 Total | Category 2 Total | Unknown Category Total
ABC 1 3 0
DEF 2 7 2