如何获得桌子上最高订单的计数?

时间:2019-03-21 21:58:02

标签: mysql sql

sql的新手,我正在寻找一些见识。我们有与“ customer_type”相关联的客户。我希望吸引所有具有该特定类型的客户,并输出从我们那里订购的该类型的前10名最高客户。我能够做到这一点,但我对从哪里去获得该计数感到困惑。

SELECT T1.customer_id, T1.customer_name, T1.customer_type, T2.order_id
FROM customers T1
INNER JOIN sales_orders T2 ON T1.customer_id = T2.customer_id
WHERE T1.customer_type = 'R'
ORDER BY
T1.customer_id,
T1.customer_name,
T2.order_id

所以基本上,这是这样输出的:

customer A = customer name A = type = order_id A
customer A = customer name A = type = order_id A
customer A = customer name A = type = order_id A
customer B = customer name B = type = order_id B
customer B = customer name B = type = order_id B
customer C = customer name C = type = order_id C

等等。该怎么做才能将其合并,仅找出具有最多order_id的前十名?

1 个答案:

答案 0 :(得分:0)

SELECT T1.customer_id, T1.customer_name, T1.customer_type, T2.order_id
FROM customer T1
INNER JOIN sale_orders T2 ON T1.customer_id = T2.customer_id
WHERE T1.customer_type = 'R'
GROUP BY customer_id
ORDER BY customer_id

对于我来说,每位客户仅显示一个条目,如果您想要销售量:

SELECT T1.customer_id, T1.customer_name, T1.customer_type, T2.order_id ,COUNT(*)
FROM customer T1
INNER JOIN sale_orders T2 ON T1.customer_id = T2.customer_id
WHERE T1.customer_type = 'R'
GROUP BY customer_id
ORDER BY customer_id