从Mysql表中获取前5名客户

从Mysql表中获取前5名客户,mysql,Mysql,我有一个表“tbl_orders”,该表包含以下内容 order_id | customer_id | grand_total 现在我需要找到前五名客户,他们有更多的订单 SELECT customer_id , count(customer_id) as total_orders FROM `tbl_order` GROUP BY customer_id ORDER BY total_orders DESC LIMIT 5 我尝试下面的查询 "SELECT customer_id , c

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

order_id | customer_id | grand_total
现在我需要找到前五名客户,他们有更多的订单

SELECT customer_id , count(customer_id) as total_orders 
FROM `tbl_order` GROUP BY customer_id ORDER BY total_orders DESC LIMIT 5
我尝试下面的查询

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

但是这个查询只会给我每个客户的所有客户id和总订单&我想获得前5名客户,即我有更多订单

除了DonCallisto的答案之外,您可能还想按订单的最高数量排序。否则你将无法进入前5名

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

请注意,我还将count列从customer\u id更改为order\u id。这在功能上没有任何区别,但对阅读您的代码的人来说更有意义。

除了DonCallisto的答案之外,您可能还希望按订单的最大数量进行排序。否则你将无法进入前5名

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

请注意,我还将count列从customer\u id更改为order\u id。这在功能上没有任何区别,但对阅读您的代码的人来说更有意义。

aha感谢它的工作,但是您的语法中有错误,order BY total\u orders应该在DESC group BY customer\u id之后,但您将其放在前面:)@Arif:yes,我原以为我做到了现在的样子。你现在做得好,非常感谢你帮助我。谢谢它的工作,但是你的语法顺序有错误,按总数计算。你的订单应该在客户id描述组之后,但你把它放在前面:)@Arif:是的,我原以为我现在就做了。你现在做得好,非常感谢你帮助我