如何对一个SQL查询的结果与其他表的数据进行排序

时间:2019-11-05 20:08:45

标签: sql join sql-order-by

我有一个包含两个表的数据库。在一张桌子上,我用一栏显示了顾客的信息 costumer_id和一列costumer_name,我有一个带有客户订单的表,列order_idcustomer_id。表格如下:

客户:

+-------------+---------------+
| customer_id | customer_name |
+-------------+---------------+
|           1 | Joe           |
|           2 | Michael       |
|           3 | Ben           |
+-------------+---------------+

订单:

+----------+-------------+
| order_id | customer_id |
+----------+-------------+
|        1 |           1 |
|        2 |           2 |
|        3 |           3 |
+----------+-------------+

我现在有以下查询,它向我提供了每个客户的订单量。结果由customer_id排序。

SELECT customer_id, COUNT(order_id) 
FROM Orders 
GROUP BY customer_id 
ORDER BY customer_id ASC;

现在,我希望通过查询从Customer表中的customer_name对结果进行排序。我该如何实现?

1 个答案:

答案 0 :(得分:1)

您可以使用ID:

SELECT c.customer_name name
       , COUNT(order_id) sumarum
       , o.customer_id id
FROM Orders O
left join Customers C
on o.customer_id = c.customer_id
GROUP BY customer_name, o.customer_id
ORDER BY c.customer_name, o.customer_id;

或者没有ID(只需输入名称和计数):

select name
       , sumarum
from (SELECT o.customer_id id
       , COUNT(order_id) sumarum
       , c.customer_name name
FROM Orders O
left join Customers C
on o.customer_id = c.customer_id
GROUP BY customer_name, o.customer_id
ORDER BY c.customer_name, o.customer_id);

这里是DEMO