Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.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 选择表中的最高值_Sql_Db2 - Fatal编程技术网

Sql 选择表中的最高值

Sql 选择表中的最高值,sql,db2,Sql,Db2,所以,我有一个疑问 select C.custID, C.custName, count(C.custID) as totalOrder from Customer C, Purchase P where C.custID = P.custID and P.purchaseDate between '2015-01-01' and '2015-12-31' group by C.custID, C.custName 此查询显示客户的所有记录。如何修改此查询,使其仅显示totalOrder最高的

所以,我有一个疑问

select C.custID, C.custName, count(C.custID) as totalOrder from Customer C, Purchase P
where C.custID = P.custID and P.purchaseDate between '2015-01-01' and '2015-12-31'
group by C.custID, C.custName
此查询显示客户的所有记录。如何修改此查询,使其仅显示totalOrder最高的客户记录


我可以尝试使用
having count(C.custID)=…
但是我不知道还能做什么

您可以使用子选择来做这件事(和
连接来进一步优化它)

另外,希望我不是太烦人,但我不确定您是否应该按客户ID和姓名分组。ID应该足够了。如果客户可以具有相同的ID和不同的名称,那么按两者进行分组就可以了。像
ID1,名字约翰
ID1,名字杰夫
。如果是这样的话,可能就不是这样了:P

无论如何,我建议你试试这个:

SELECT total_orders.custID, total_orders.custName, MAX(total_orders.totalOrder) FROM (SELECT c.custID, c.custName, count(c.custID) as totalOrder FROM Customer c LEFT JOIN Purchase p ON c.custID = p.custID WHERE p.purchaseDate BETWEEN '2015-01-01' AND '2015-12-31' GROUP BY c.custID, c.custName) as total_orders

首先,选择并计算与之前相同的值,但将其存储为一种虚拟表(将
select…FROM()作为something
执行,其中
something
是虚拟表),从中选择
MAX(totalOrder)

已解决。我想是这样的:

select C.custID, C.custName, count(C.custID) as totalOrder from Customer C, Purchase P
where C.custID = P.custID and P.purchaseDate between '2015-01-01' and '2015-12-31'
group by C.custID, C.custName having count(C.custID) = 
(select max(t.totalOrder) from 
(select C.custID, C.custName, count(C.custID) as totalOrder from Customer C, Purchase P
where C.custID = P.custID and P.purchaseDate between '2015-01-01' and '2015-12-31'
group by C.custID, C.custName) t)
注意,我添加了

having count(C.custID) = 
(select max(t.totalOrder) from 
(select C.custID, C.custName, count(C.custID) as totalOrder from Customer C, Purchase P
where C.custID = P.custID and P.purchaseDate between '2015-01-01' and '2015-12-31'
group by C.custID, C.custName) t)
所以它会找到totalOrder的最大值。而
count(C.custID)
将被分配给totalOrder的最大值。这可能是一个相当糟糕的代码,但它可以工作


如果有人有更简单的方法来解决这个问题,请分享代码。

这不起作用,先生。它给了我这个错误<代码>在GROUP BY子句中未指定以SELECT子句、HAVING子句或ORDER BY子句中指定的“CUSTNAME”开头的表达式,或者在具有列函数的SELECT子句、HAVING子句或ORDER BY子句中未指定GROUP BY子句。SQLSTATE=42803