使用GROUP BY / HAVING重构子查询?

时间:2009-02-04 15:36:17

标签: sql mysql refactoring query-optimization

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

3 个答案:

答案 0 :(得分: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,false等于0.我也使用了BETWEEN运算符,这个运算符要快一点。

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

select Title, CategoryID, count(*)
from entries
WHERE Date BETWEEN @StartDate AND @EndDate
group by Title, CategoryID

答案 1 :(得分:0)

Select COUNT(*), sTitle, CategoryID FROM entries 
WHERE Date >= @StartDate and Date <= @EndDate 
GROUP BY CategoryID, sTitle

答案 2 :(得分:0)

如何按类别ID进行分组,然后使用having语句过滤掉特定类别,例如:

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
相关问题