我遇到过以下 SYBASE SQL:
-- Setup first
create table #t (id int, ts int)
go
insert into #t values (1, 2)
insert into #t values (1, 10)
insert into #t values (1, 20)
insert into #t values (1, 30)
insert into #t values (2, 5)
insert into #t values (2, 13)
insert into #t values (2, 25)
go
declare @time int select @time=11
-- This is the SQL I am asking about
select * from (select * from #t where ts <= @time) t group by id having ts = max(ts)
go
这条SQL的结果是
id ts
----------- -----------
1 10
2 5
这看起来像是 HAVING 条件应用于行而不是组。有人可以指出 Sybase 15.5 文档中描述此案例的位置吗?我所看到的只是“HAVING 对组进行操作”。我在文档中看到的最接近的是:
having 子句可以包含不在其中的列或表达式
选择列表而不是在 group by 子句中。
(引自here http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_15.0.commands/html/commands/commands60.htm).
然而,他们并没有准确解释当你这样做时会发生什么。
我的理解:是的,从根本上来说,HAVING 是对行进行操作的。通过省略 GROUP BY,它对单个“超级组”内的所有结果行进行操作,而不是对组内的行进行操作。阅读本节“分组依据和聚合查询如何工作”在您最初链接的 Sybase docco 中:-
分组依据和聚合查询如何工作
- The where子句排除不满足其搜索条件的行;对于分组或非分组查询,其功能保持不变。
- The group by子句将剩余行收集到一组中的每个唯一值group by表达。省略group by为整个表创建一个组。
- 选择列表中指定的聚合函数计算每个组的汇总值。对于标量聚合,表中只有一个值。向量聚合计算不同组的值。
- The having clause excludes groups from the results that do not meet its search conditions. Even though the having clause tests only rows, the presence or absence of a group by clause may make it appear to be operating on groups:
- 当查询包含group by, having排除结果组行。这就是为什么having似乎是对团体进行操作。
- 当查询没有group by, having从(单组)表中排除结果行。这就是为什么having似乎对行进行操作(结果类似于where子句结果)。
其次,该部分中出现一个简短的摘要“having、group by 和 where 子句如何相互作用” http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_15.0.sqlug/html/sqlug/sqlug122.htm:-
having、group by 和 where 子句如何相互作用
当您包括having, group by, and where查询中的子句,每个子句影响行的顺序决定了最终结果:
- The where子句排除不满足其搜索条件的行。
- The group by子句将剩余行收集到一组中的每个唯一值group by表达。
- 选择列表中指定的聚合函数计算每个组的汇总值。
- The having子句从最终结果中排除不满足搜索条件的行。
@SQLGuru 的解释就是对此的说明。
Edit...
与此相关的是,我对利用 TSQL“扩展列”的不符合 ANSI 的查询的行为感到惊讶。 Sybase 处理扩展列(i)在 WHERE 子句之后(ii)通过创建与原始表的额外连接以及(iii)连接中不使用 WHERE 子句。此类查询可能返回比预期更多的行,然后 HAVING 子句需要附加条件来过滤掉这些行。
查看示例b, c and d under “对 group by 和having 的 Transact-SQL 扩展”在您最初链接的 docco 的页面上。我发现安装它很有用pubs2来自 Sybase 的示例数据库与示例一起使用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)