WHERE子句中的COUNT还是HAVING?

时间:2013-05-10 08:48:57

标签: sql sql-server-2008-r2

这基本上就是我想要实现的目标;

SELECT 
COUNT(DISTINCT No) 
FROM 
Table 
WHERE 
(Type = 1 AND COUNT(DISTINCT No) > Num) 
OR (Type = 2 AND COUNT(DISTINCT No) > Num) 
GROUP BY
Week

实现这一目标的最佳方式是什么?

由于

3 个答案:

答案 0 :(得分:2)

任何聚合比较都需要在Group By之后进入HAVING子句。请记住,根据您放置非聚合条件的位置,您可能会得到不同的结果,因为您将汇总您通过WHERE包含/排除的内容。

SELECT COUNT(DISTINCT No) 
FROM Table 
WHERE Type = 1
GROUP BY Week
HAVING COUNT(DISTINCT No) > Num

可能与

不同
SELECT COUNT(DISTINCT No) 
FROM Table 
GROUP BY Week
HAVING COUNT(DISTINCT No) > Num
AND Type = 1

答案 1 :(得分:0)

使用此:

SELECT 
COUNT(DISTINCT No) as num1
FROM TableName
WHERE Type IN (1,2)  
GROUP BY Week
HAVING num1 > Num

答案 2 :(得分:0)

  SELECT Week, Type, COUNT(DISTINCT No) WeekTally
    FROM   [Table]
   WHERE  Type in (1,2)
GROUP BY Week, Type
  HAVING COUNT(DISTINCT No) > @Num
ORDER BY Week, Type;

如果你按周进行分组,肯定你想看看这个星期是哪个星期?!