【发布时间】:2009-02-04 15:36:17
【问题描述】:
我正在构建一个 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
【问题讨论】:
-
你能提供一个示例结果集吗?
标签: sql mysql refactoring query-optimization