Answered Count CustomersOrders

  • Friday, October 14, 2005 6:19 AM
     
     
    Dear Team
      if there are three tables customers, Order  and OrderDetails
      how to count the number of orders for each certain customer

     Thank you very much

All Replies

  • Friday, October 14, 2005 12:00 AM
     
     Answered
    Assuming you have the CustomerID in the Orders table as a foreign key back to the Customers table, you can do a group by on the Orders.CustomerID and do a count. Using the Northwind database schema:
     

    select CustomerID, count(OrderID)
    from Orders
    group by CustomerID

    This will only give you results for the customers that have orders. If you need the customers without orders as well, you will need to include the Customers table. For example with a left outer join:

    select C.CustomerID, count(O.OrderID)
    from Customers C left outer join Orders O on C.CustomerID=O.CustomerID
    group by C.CustomerID

    Best regards

    Michael

    Dear Team
      if there are three tables customers, Order  and OrderDetails
      how to count the number of orders for each certain customer

     Thank you very much
  • Friday, October 14, 2005 12:44 PM
     
     
    Mr NNTP
     The Query looks good thank you very much
     i will take some time to test it