0

我有一个表'tbl_orders',该表包含以下内容

order_id | customer_id | grand_total

现在我需要找出与我有更多订单的 TOP 5 客户

我尝试下面的查询,

"SELECT customer_id , count(customer_id) as total_orders FROM `tbl_order` group by customer_id"

但是这个查询只给了我每个客户的所有 customer_id 和 total_orders 并且我想获取 TOP 5 客户,即我有更多订单

4

2 回答 2

3

添加到 DonCallisto 的答案中,您可能还希望按最高订单数进行排序。不然进不了前五。

SELECT customer_id , count(order_id) as total_orders 
FROM `tbl_order` 
GROUP BY customer_id 
ORDER BY total_orders DESC
LIMIT 5

请注意,我还将计数列从 customer_id 更改为 order_id。这在功能上没有任何区别,但对于阅读您的代码的人来说更有意义。

于 2012-05-09T07:56:40.777 回答
2
SELECT customer_id , count(customer_id) as total_orders 
FROM `tbl_order` GROUP BY customer_id ORDER BY total_orders DESC LIMIT 5
于 2012-05-09T07:48:00.923 回答