繁体   English   中英

SQL MAX() 函数未按预期工作

[英]SQL MAX() Function Not Working As Expected

我试图为每个customer组选择最大requester_req ,但在尝试了多种不同的方法后,我的结果集继续显示每一行而不是客户组的最大值。

查询:

SELECT 
x2.customer, 
x.customer_req, 
x2.requester_name, 
MAX(x2.requester_req) AS requester_req

FROM x, x2

WHERE x.customer = x2.customer

GROUP BY x2.customer, x2.requester_name, x.customer_req

ORDER BY x2.customer

示例结果集:

customer          customer_req          requester_name          requester_req
Bob's Burgers     7                     Bob                     9
Bob's Burgers     7                     Jon                     12
Hello Kitty       9                     Jane                    3
Hello Kitty       9                     Luke                    7

预期结果集:

customer          customer_req          requester_name          requester_req
Bob's Burgers     7                     Jon                     12
Hello Kitty       9                     Luke                    7

我在 group by 条款中搞砸了什么吗? 我无法计算我已经切换了多少次并获得相同的结果集。

非常感谢您的帮助!

为每个客户组选择最大 requester_req

不要聚合。 相反,您可以使用相关子查询进行过滤:

select 
    x2.customer, 
    x.customer_req, 
    x2.requester_name, 
    x2.requester_req
from x
inner join x2 on x.customer = x2.customer
where x2.requester_req = (
    select max(x20.requester_req) from x2 x20 where x20.customer = x2.customer
)
order by x2.customer

旁注:始终使用显式的标准连接(使用on关键字)而不是老式的隐式连接(在from子句中使用逗号):20 多年来不再推荐使用这种语法,主要是因为它更难遵循.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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