简体   繁体   中英

arithmetic operator in SQL HAVING clauses

Can I have arithmetic operator in SQL having clause? Because from what i know arithmetic operators are only allowed in SELECT and WHERE clause. But the following code make sense to me though, but I know it serves no purpose. Any advice?

 SELECT E.name
 FROM Example E
 GROUP BY E.name
 HAVING COUNT(*) + 2 > 4

If you want a more complicated arithmetic expression, you can use a subquery:

select
    *
from
(
    select
        cnt = COUNT(*) + 2
        , E.Name
    from
        Example E
    group by
        E.name
) as subQ
where
    subQ.cnt > 4

Yes, you can use "arithmetic operator" in a HAVING clause.

The expression in the HAVING clause will be evaluated as a boolean.


NOTE: be sure the order of precedence is what you expect, eg

( COUNT(*) + 2 ) > 4 

vs

COUNT(*) + ( 2 > 4 )

In your example, the addition isn't really required; the expression could be replace with the logically equivalent:

COUNT(*) > 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM