Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL MAX()函数未按预期工作_Sql_Join_Group By_Max_Greatest N Per Group - Fatal编程技术网

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

SQL MAX()函数未按预期工作,sql,join,group-by,max,greatest-n-per-group,Sql,Join,Group By,Max,Greatest N Per Group,我试图为每个客户组选择maxrequester_req,但是在尝试了许多不同的方法之后,我的结果集继续显示每一行,而不是客户组的max 查询: 示例结果集: 预期结果集: 我有没有在小组里搞砸了什么?我记不清有多少次我把事情调好,得到了相同的结果集 非常感谢你的帮助 为每个客户组选择最大请求者请求 不要聚集在一起。相反,您可以使用相关子查询进行筛选: select x2.customer, x.customer_req, x2.requester_name,

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

查询: 示例结果集: 预期结果集: 我有没有在小组里搞砸了什么?我记不清有多少次我把事情调好,得到了相同的结果集

非常感谢你的帮助

为每个客户组选择最大请求者请求

不要聚集在一起。相反,您可以使用相关子查询进行筛选:

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多年了,不再推荐了,主要是因为它更难理解。

你是一个救命恩人。我不敢相信我竟然没有想到这个。。。doh。一旦10分钟计时器启动,将接受此答案。:)再次感谢你!请使用SQL-92(27年前)提供的现代联接语法。是:您的group by子句要求为(客户、请求者名称、客户请求)的每个唯一组合生成一行。您可以在结果集中看到,每行的request_name字段都不同。您期望的结果是每个客户只需要一行。您可以通过从组中删除requester_name和customer_req,或者在select中添加聚合函数,或者也可以从select中删除它们。请解释您期望的原因。否则我们只能猜测你的误解。PS请在代码问题中给出一个--cut&paste&runnable代码,包括作为代码输入的最小代表性示例;期望和实际输出(包括逐字记录错误消息);标签和版本;清晰的说明和解释。对于包含DBMS和DDL(包括约束和索引)的SQL,请将其输入为格式化为表的代码。
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
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