我有一个表'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&每个客户的总数和我想获取TOP 5客户,即与我订购更多订单
答案 0 :(得分:3)
添加到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_id更改为order_id。这在功能上没有任何区别,但对于阅读代码的人来说更有意义。
答案 1 :(得分:2)
SELECT customer_id , count(customer_id) as total_orders
FROM `tbl_order` GROUP BY customer_id ORDER BY total_orders DESC LIMIT 5