我正在尝试为每个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, 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子句中搞砸了吗?我无法数出切换次数并获得相同结果集的次数。
非常感谢您的帮助!
答案 0 :(得分:3)
为每个客户组选择最大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年,主要是因为很难遵循。