Reputation: 23
I built this query to show me how many employees and customers to a branch, it gives me duplicates therefore I need to group them. However, the query is invalid when I add the group by. Anyone have any idea why?
SELECT B.branchID, B.branchName, COUNT(E.staffNo) AS "No. Of Employees", COUNT(C.customerID) AS "No. Of Customers"
FROM Branch B, Employee E, Customer C
WHERE E.employeeBranchID = B.branchID
AND B.branchID = C.customerBranchID
GROUP BY B.branchID;
Upvotes: 0
Views: 579
Reputation: 1271003
This query would be better written as:
SELECT B.branchID, B.branchName, COUNT(E.staffNo) AS "No. Of Employees", COUNT(C.customerID) AS "No. Of Customers"
FROM Branch B JOIN
Employee E
ON E.employeeBranchID = B.branchID JOIN
Customer C
ON B.branchID = C.customerBranchID
GROUP BY B.branchID, B.branchName;
If you are in ANSI mode, then MySQL behaves like most other databases and will return an error because B.branchName
is unaggregated.
Notes:
JOIN
syntax. Never use commas in the FROM
clause.GROUP BY
.branchId
is declared as the primary or a unique key on branch
. However, most databases still do not accept the query.Upvotes: 2
Reputation: 881
SELECT B.branchID, B.branchName, COUNT(E.staffNo) AS "No. Of Employees", COUNT(C.customerID) AS "No. Of Customers" FROM Branch B left join Employee E on E.employeeBranchID = B.branchID left join Customer C on B.branchID = C.customerBranchID GROUP BY B.branchID;
Upvotes: 0
Reputation: 1393
SELECT B.branchID, B.branchName, COUNT(E.staffNo) AS "No. Of Employees", COUNT(C.customerID) AS "No. Of Customers"
FROM Branch B, Employee E, Customer C
WHERE E.employeeBranchID = B.branchID
AND B.branchID = C.customerBranchID
GROUP BY B.branchID, B.branchName;
Most DB require the list of group by items == the list of items in select before an aggregation function
Upvotes: 0