简体   繁体   中英

SQL - Find total number of orders made for each customer

I have 2 tables customer and orders . Each customer can place multiple orders

  • customer has a column customer_num
  • orders has columns order_num, customer_num

I want the results to show like this:

在此处输入图像描述

Here is my current code which only returns all the distinct customer num

select distinct c.customer_num  
from customer c 
inner join orders o on o.CUSTOMER_NUM = c.customer_num

Try the below - using count() aggregation with group by

select c.customer_num,count(order_num) 
from customer c inner join orders o on  o.CUSTOMER_NUM = c.customer_num
group by c.customer_num

Assuming you are only interested in customers who actually ordered something, to get your desired result, you don't even need to involve table customer. Just:

SELECT customer_num, count(*) AS orders_made
FROM   orders
GROUP  BY customer_num
ORDER  BY customer_num;  -- seems like you want this order?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM