0

我正在构建一个 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
4

3 回答 3

3
select Title, SUM(CategoryID=1) as Cat1, SUM(categoryID=2) as Cat2,
SUM(categoryID IS NULL) as UnknownCategory
FROM entries
WHERE Date BETWEEN @StartDate AND @EndDate
GROUP BY Title

您可以在 sum() 函数中粘贴表达式:真值等于 1,假值等于 0。我还使用了速度更快的 BETWEEN 运算符。

一种会返回不同结果布局但在概念上更简单的替代方案:

select Title, CategoryID, count(*)
from entries
WHERE Date BETWEEN @StartDate AND @EndDate
group by Title, CategoryID
于 2009-02-04T16:02:32.837 回答
0
Select COUNT(*), sTitle, CategoryID FROM entries 
WHERE Date >= @StartDate and Date <= @EndDate 
GROUP BY CategoryID, sTitle
于 2009-02-04T15:41:17.277 回答
0

如何按类别 id 分组,然后使用 have 语句过滤掉特定类别,例如:

select CategoryID, count(*) 
from entries 
where Date >= @StartDate AND Date <= @EndDate
group by CategoryID
having CategoryID = 1 or CategoryID = 2 or CategoryID is null

如果每个类别有多个标题,您可以按两个字段分组:

select Title, CategoryID, count(*) 
from entries 
where Date >= @StartDate AND Date <= @EndDate
group by Title, CategoryID
having CategoryID = 1 or CategoryID = 2 or CategoryID is null
于 2009-02-04T15:51:13.967 回答