Reputation: 3260
My tables:
Customers
:
+------+----+
| Name | ID |
+------+----+
| Phu | 12 |
| Nam | 23 |
| Mit | 33 |
+------+----+
Orders
:
+----+------------+
| ID | Order |
+----+------------+
| 12 | Laptop |
| 12 | Mouse |
| 33 | Smartphone |
| 23 | Keyboard |
| 33 | Computer |
+----+------------+
I want to get output like this:
+------+--------+
| Name | Orders |
+------+--------+
| Phu | 2 |
| Mit | 2 |
+------+--------+
I use this query but this doesn't work:
SELECT
Name,
COUNT(*) AS 'Orders'
FROM
Orders a
INNER JOIN
Customers b ON a.ID = b.ID
GROUP BY
a.ID
HAVING
COUNT(*) > 1;
It has the error like this:
Column 'Customers.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Any help is really appreciated. Thank you.
Upvotes: 0
Views: 154
Reputation: 17927
SELECT c.Name, COUNT(o.ID) AS Orders
FROM Customers c INNER JOIN Orders o ON c.ID = o.ID
GROUP BY o.ID
HAVING Orders > 1
Working Sqlfiddle: http://sqlfiddle.com/#!2/869790/4
Upvotes: 1
Reputation: 2156
As mentioned in my comment every column in the select statement has to be in the group by clause.
SELECT Name, COUNT(*) AS 'Orders'
FROM Orders a
INNER JOIN Customers b
ON a.ID = b.ID
GROUP BY b.Name
HAVING COUNT(*)>1;
Upvotes: 0