我正在构建一个 MySQL 查询以确定在给定日期范围内出现的几个类别中的每个类别中有多少项目。我最初的尝试是这样的:
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
该表非常大,我想重构查询以加快速度,但我不确定如何使用 GROUP BY/HAVING 语句重写它,还是有另一种我遗漏的方法?
编辑:示例结果集 - 像这样:
Title | Category 1 Total | Category 2 Total | Unknown Category Total
ABC 1 3 0
DEF 2 7 2