-1

I am pretty new to SQL.

When I have a list like this

+----+------+
| id | name |
+----+------+
| 1  | Mike |
+----+------+
| 1  | Mike |
+----+------+
| 2  | Mike |
+----+------+
| 2  | Mike |
+----+------+
| 2  | Mike |
+----+------+
| 5  | Sam  |
+----+------+
| 6  | Sam  |
+----+------+
| 7  | Sam  |
+----+------+
| 7  | Sam  |
+----+------+

and I want to count how many unique Mikes and Sams there are. So the output would be

+------+---+
| Mike | 2 |
+------+---+
| Sam  | 3 |
+------+---+

How would I do that?

Edit:

This was just an example for my problem. The code would be something like SELECT id, name FROM id, name WHERE some conditions

And I tried something like SELECT id, name, COUNT(*) From id,name WHERE some conditions GROUP BY id, name

and the output is not what I want. It just counts how many Mikes and Sams there are. But I want how many unique Mikes and Sams there are

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
A. Aoe
  • 11
  • 3

1 Answers1

1
SELECT name, COUNT(DISTINCT id) AS cnt
FROM mytable
GROUP BY name
HAVING COUNT(DISTINCT id) > 1

The syntax may vary for your database server but the point will be the same: Count the number of unique ID values per name, filter those that have more than one.

If your database server does not have COUNT DISTINCT:

SELECT name, COUNT(*) AS cnt
FROM (SELECT DISTINCT id, name
      FROM mytable)
GROUP BY name
HAVING COUNT(*) > 1
user2722968
  • 13,636
  • 2
  • 46
  • 67
  • Why `HAVING COUNT(DISTINCT id) > 1` ? – Oto Shavadze Jul 22 '17 at 20:31
  • I'm assuming that, while not shown in the example but suggested in the topic provided by op, he is after duplicates. Those will have a `COUNT(DISTINCT id)` greater than one. – user2722968 Jul 22 '17 at 20:33
  • Ahh that nearly is it! Just without the HAVING clause. I needed that Distinct, totally didn't think of that. Thank you very much – A. Aoe Jul 22 '17 at 20:38