[英]SQL - HAVING Clause in depth
I'm trying to understand what condition can be placed after the having clause - it is usually a condition, that uses the functions from the select statement, but it also can contain a column, that is typed in the select statement. 我试图了解可以在hading子句之后放置什么条件-它通常是一个条件,使用select语句中的函数,但它也可以包含在select语句中键入的列。
Here's an example: 这是一个例子:
create table r(a int, b int, c int, d int, e int primary key)
select a, min(b), sum(c)
from r
where b > 5
group by a
having "condition"
which of the following can replace the "condition" 以下哪项可以代替“条件”
a) b = 5
b) a = sum(e)
c) min(b) >= 6
When I execute this in SQL, only a) doesn't work, but what's the logic behind it? 当我在SQL中执行此操作时,只有a)不起作用,但是其背后的逻辑是什么?
This will be correct one 这将是正确的
create table r(a int, b int, c int, d int, e int primary key)
select a, min(b), sum(c)
from r
where b > 5
group by a
having "min(b) >= 6"
The HAVING
clause is applied as a filter after the GROUP BY
. HAVING
子句在GROUP BY
之后用作过滤器。
If you keep that in mind, it becomes obvious that: 如果您牢记这一点,那么显而易见的是:
b=5
fails because you don't GROUP BY b
in the query and b
is used as-is and not in an aggregation function. b=5
失败,因为您没有在查询中使用GROUP BY b
,并且b
按原样使用,而不是在聚合函数中使用。
a=SUM(e)
succeeds because you GROUP BY a
and compare a
with an aggregate function. a=SUM(e)
成功是因为您对GROUP BY a
比较,然后将a
与聚合函数进行a
比较。
MIN(b) >= 6
succeeds because you compare an aggregate function with a constant. MIN(b) >= 6
成功,因为您将聚合函数与常量进行了比较。
Hope this clarifies ... 希望这可以澄清...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.