[英]SQL MAX() Function Not Working As Expected
I am attempting to select the max requester_req
for each customer
group, but after trying numerous different approaches, my result set continues to display every row instead of the max for the customer group.我试图为每个
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
Have I screwed up something in my group by clause?我在 group by 条款中搞砸了什么吗? I can't count how many times I've switched things up and get the same result set.
我无法计算我已经切换了多少次并获得相同的结果集。
Thank you very much for your help!非常感谢您的帮助!
select the max requester_req for each customer group
为每个客户组选择最大 requester_req
Don't aggregate.不要聚合。 Instead, you can filter with a correlated subquery:
相反,您可以使用相关子查询进行过滤:
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
Side note: always use explicit, standard joins (with the on
keywords) instead of old-school implicit joins (with commas in the from
clause): this syntax is not recommended anymore since more than 20 years, mostly because it is harder to follow.旁注:始终使用显式的标准连接(使用
on
关键字)而不是老式的隐式连接(在from
子句中使用逗号):20 多年来不再推荐使用这种语法,主要是因为它更难遵循.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.