Using the COUNT function in SQL

前端 未结 5 1040
猫巷女王i
猫巷女王i 2021-01-25 00:24

First and Foremost, this is part of an assignment.

I am trying to use the COUNT function as part of a query in relation to the Northwind database. The query should retur

5条回答
  •  深忆病人
    2021-01-25 01:06

    You need a group by clause, which will allow you to split your result in to groups, and perform the aggregate function (count, in this case), per group:

    SELECT   Customers.CustomerID, Customers.CompanyName, COUNT(*)
    FROM     Orders, Customers
    WHERE    Customers.CustomerID = Orders.CustomerID;
    GROUP BY Customers.CustomerID, Customers.CompanyName
    

    Note: Although this is not part of the question, it's recommended to use explicit joins instead of the deprecated implicit join syntax you're using. In this case, the query would look like:

    SELECT   Customers.CustomerID, Customers.CompanyName, COUNT(*)
    FROM     Orders
    JOIN     Customers ON Customers.CustomerID = Orders.CustomerID;
    GROUP BY Customers.CustomerID, Customers.CompanyName
    

提交回复
热议问题