HAVING子句中的多个聚合函数

时间:2013-02-07 16:37:54

标签: mysql sql count

由于我的查询的性质,我的记录计数为3,也符合计数为2的标准,依此类推。我想知道是否可以查询“计数超过x且小于7”?我怎么能写这个。这是我目前的代码。

GROUP BY meetingID
HAVING COUNT( caseID )<4

我想要像

这样的东西
GROUP BY meetingID
HAVING COUNT( caseID )<4 AND >2

那样它只计算3

6 个答案:

答案 0 :(得分:54)

GROUP BY meetingID
HAVING COUNT(caseID) < 4 AND COUNT(caseID) > 2

答案 1 :(得分:8)

没有必要进行两次检查,为什么不检查count = 3:

GROUP BY meetingID
HAVING COUNT(caseID) = 3

如果您想使用多项检查,则可以使用:

GROUP BY meetingID
HAVING COUNT(caseID) > 2
 AND COUNT(caseID) < 4

答案 2 :(得分:3)

对于您的示例查询,唯一可能的值大于2且小于4是3,因此我们简化:

GROUP BY meetingID
HAVING COUNT(caseID) = 3

在一般情况下:

GROUP BY meetingID
HAVING COUNT(caseID) > x AND COUNT(caseID) < 7

或者(可能更容易阅读?),

GROUP BY meetingID
HAVING COUNT(caseID) BETWEEN x+1 AND 6

答案 3 :(得分:1)

这样的东西?

HAVING COUNT(caseID) > 2
AND COUNT(caseID) < 4

答案 4 :(得分:1)

在这里,我正在撰写完整的查询,这将清除您的所有怀疑

SELECT BillingDate,
       COUNT(*) AS BillingQty,
       SUM(BillingTotal) AS BillingSum
FROM Billings
WHERE BillingDate BETWEEN '2002-05-01' AND '2002-05-31'
GROUP BY BillingDate
HAVING COUNT(*) > 1
AND SUM(BillingTotal) > 100
ORDER BY BillingDate DESC

答案 5 :(得分:-1)

select CUSTOMER_CODE,nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) DEBIT,nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) CREDIT,
nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) BALANCE from TRANSACTION   
GROUP BY CUSTOMER_CODE
having nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) > 0
AND (nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0))) > 0