SQL MAX()函数无法按预期工作 查询:样本结果集:预期结果集:

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

查询:

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,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子句中搞砸了吗?我无法数出切换次数并获得相同结果集的次数。

非常感谢您的帮助!

crediblebridge 回答:SQL MAX()函数无法按预期工作 查询:样本结果集:预期结果集:

  

为每个客户组选择最大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年,主要是因为很难遵循。

本文链接:https://www.f2er.com/2960024.html

大家都在问