I have a table containing order data as follows (simplified):
ID CustomerID OrderId
1 1 100
2 1 101
3 1 102
4 2 103
5 3 104
6 2 105
I want to write a query that collates all of the unique customerIds present in this table and counts the amount of orders that each customer has. But I'm struggling with how to go about this.
Select distinct customerId from table
The above will give me all of the unique customerIds in the table, but then I'm not sure how to aggregate the counts of each customer's orders onto this data. Am I right in thinking it involves some kind of subquery?
You need COUNT
and GROUP BY
. Try like:
SELECT CustomerID,COUNT(*) FROM myTable GROUP BY customerID
You are describing group by
:
Select customerId, count(*)
from table
group by customerId;
This is a quite basic part of SQL syntax. You may want to brush up on your SQL.
Simple aggregation with group by
clause :
select customerId, count(*) as orders
from table
group by customerId;
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.