0

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.

2
  • 1
    Every column you select has to be in the group by clause. So use Group by b.Name Commented Oct 24, 2014 at 9:34
  • It's a query (not a querry - one r is quite enough) Commented Oct 24, 2014 at 11:25

2 Answers 2

1
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

Sign up to request clarification or add additional context in comments.

Comments

0

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; 

2 Comments

If same name in customer table then what happen?
Then group by Id first. GROUP BY a.Id, b.Name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.