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
When using aggregate functions like COUNT(), all columns have to be part of aggregate functions. The GROUP BY
statement should solve your problem. http://www.w3schools.com/sql/sql_groupby.asp
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 join
s 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
The below query should work.
SELECT Customers.CustomerID, Customers.CompanyName, COUNT(*)
FROM Orders, Customers
WHERE Customers.CustomerID = Orders.CustomerID group by Orders.CustomerID
First, if you are learning SQL, you should learn proper explicit join
syntax. Simple rule: never use a comma in the from
clause.
Second, your query should use group by
instead of distinct
. In fact, it is more important to learn group by
than to learn distinct
, because you can generally write select distinct
using group by
.
So, where you are heading is:
SELECT c.CustomerID, c.CompanyName, COUNT(c.CustomerID)
FROM Orders o JOIN
Customers c
ON c.CustomerID = o.CustomerID
GROUP BY c.CustomerID, c.CompanyName;
You are missing the group by
clause. Your query should look like this
select CustomerID, Customers.CompanyName, count(CustomerID)
from Orders JOIN Customers using(CustomerID)
group by CustomerID;
Notice that I used the Join
syntax which is more concise when joining tables.