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