Sql Server:如何在 WHERE 子句中使用 MAX 等聚合函数
我想获得该记录的最大值。请帮我:
SELECT rest.field1
FROM mastertable AS m
INNER JOIN (
SELECT t1.field1 field1,
t2.field2
FROM table1 AS T1
INNER JOIN table2 AS t2 ON t2.field = t1.field
WHERE t1.field3=MAX(t1.field3)
-- ^^^^^^^^^^^^^^ Help me here.
) AS rest ON rest.field1 = m.field
I want get the maximum value for this record. Please help me:
SELECT rest.field1
FROM mastertable AS m
INNER JOIN (
SELECT t1.field1 field1,
t2.field2
FROM table1 AS T1
INNER JOIN table2 AS t2 ON t2.field = t1.field
WHERE t1.field3=MAX(t1.field3)
-- ^^^^^^^^^^^^^^ Help me here.
) AS rest ON rest.field1 = m.field
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
正如您所注意到的,
WHERE
子句不允许您在其中使用聚合。这就是HAVING
子句的用途。As you've noticed, the
WHERE
clause doesn't allow you to use aggregates in it. That's what theHAVING
clause is for.您可以使用子查询...
但我实际上会将其从 where 子句移到 join 语句中,作为 ON 子句的 AND 。
You could use a sub query...
But I would actually move this out of the where clause and into the join statement, as an AND for the ON clause.
在having子句中使用max的正确方法是首先执行自连接:
以下是使用子查询连接的方法:
处理多表连接时,请确保在使用聚合之前创建单个数据集:
Sub查询版本:
The correct way to use max in the having clause is by performing a self join first:
The following is how you would join with a subquery:
Be sure to create a single dataset before using an aggregate when dealing with a multi-table join:
Sub query version:
是的,您需要在 Group by 子句之后使用having子句,
因为 where 只是根据简单参数过滤数据,
但 group by 后跟having语句是对数据进行分组并根据某些聚合函数对其进行过滤的想法……
yes you need to use a having clause after the Group by clause ,
as the where is just to filter the data on simple parameters ,
but group by followed by a Having statement is the idea to group the data and filter it on basis of some aggregate function......
但它仍然在查询生成器中给出错误消息。我正在使用 SqlServerCe 2008。
正如 @powerlord 所说,我将 WHERE 替换为 HAVING。但仍然显示错误。
解析查询时出错。 [令牌行号 = 1,令牌行偏移 = 371,错误令牌 = SELECT]
But its still giving an error message in Query Builder. I am using SqlServerCe 2008.
I replaced WHERE with HAVING as said by @powerlord. But still showing an error.
Error parsing the query. [Token line number = 1, Token line offset = 371, Token in error = SELECT]