选择表上的最高值

时间:2016-01-31 19:02:17

标签: 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

此查询显示Customers的所有记录。如何修改此查询以便它只显示具有最高totalOrder的Customer记录?

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

2 个答案:

答案 0 :(得分:0)

您可以使用子选择来执行此操作(以及JOIN以进一步优化它。)

另外,希望我不会太讨厌,但我不确定你应该GROUP BY客户ID和名字。 ID应该足够了。如果客户可以拥有相同的ID和不同的名称,则两者分组将起作用。与ID 1, Name JohnID 1, Name Jeff一样。如果确实如此,它可能不应该是这样的: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 (<another select>) as something something虚拟表< / em>),从中选择MAX(totalOrder)

答案 1 :(得分:0)

解决。我认为它是这样的:

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的最大值。这可能是一个非常糟糕的代码,但它的工作原理。

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