HAVING 子句中的多个聚合函数

Posted

技术标签:

【中文标题】HAVING 子句中的多个聚合函数【英文标题】:Multiple aggregate functions in HAVING clause 【发布时间】:2013-01-23 06:05:40 【问题描述】:

由于我查询的性质,我有计数为 3 的记录,这些记录也符合计数为 2 的条件,依此类推。我想知道是否可以查询“计数大于 x 且小于 7”?我怎么会写这个。这是我当前的代码。

GROUP BY meetingID
HAVING COUNT( caseID )<4

我想要类似的东西

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

这样的话,它只计算 3

【问题讨论】:

【参考方案1】:
GROUP BY meetingID
HAVING COUNT(caseID) < 4 AND COUNT(caseID) > 2

【讨论】:

【参考方案2】:

对于您的示例查询,大于 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】:

不需要做两次检查,为什么不检查count = 3:

GROUP BY meetingID
HAVING COUNT(caseID) = 3

如果你想使用多重检查,那么你可以使用:

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

【讨论】:

【参考方案4】:

这样的?

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

【讨论】:

【参考方案5】:
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

【讨论】:

欢迎来到Stack Overflow!最好解释一下你做了什么。你能把它包括在你的答案中吗?谢谢!【参考方案6】:

我正在写完整的查询,这将消除您的所有疑虑

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

【讨论】:

以上是关于HAVING 子句中的多个聚合函数的主要内容,如果未能解决你的问题,请参考以下文章

为啥聚集函数不能出现在where子句中

SQL WHERE 子句中的聚合函数

SQL Server报错:选择列表中的列无效,因为该列没有包含在聚合函数或 GROUP BY 子句中

MySQL?having子句

第三章 集合与排序 3-3 为聚合结果指定条件

group by 列 聚合函数 where having