如何查询购买次数最多的客户(MYSQL)

时间:2011-03-30 16:47:10

标签: mysql

你好,我的SQL服务器中有这个表

tblPurchase = {purchaseId,idCust,total} tblCustomer = {idCust,name}

如果我想找到购买次数最多的客户名称(来自tblCustomer的名称),如何进行查询?谢谢

2 个答案:

答案 0 :(得分:1)

如果您正在寻找购买次数最多的客户(不是最大的购买总成本),您可以尝试: 已修改为包含加入

SELECT TOP 1 idCust, name, COUNT(*) AS numPurchases
FROM tblPurchase JOIN tblCustomer ON tblPurchase.idCust = tblCustomer.idCust
GROUP BY idCust, name
ORDER BY numPurchases DESC

如果您想要最大的购买金额:

SELECT TOP 1 idCust, SUM(total) AS purchaseSum
FROM tblPurchase
GROUP BY idCust
ORDER BY purchaseSum DESC

答案 1 :(得分:0)

也许您可以从以下内容开始:

select from tblPurchase order by idCust

然后在此之后添加改进。

  • 皮特