Comment puis-je obtenir un compte?
+---------+-------------+
| col1 | col2 |
+---------+-------------+
| Joe | April |
| Fred | May |
| Sam | April |
| Joe | April |
| Mark | Jan |
| Joe | Dec |
+---------+-------------+
Dans MySQL, comment puis-je compter sur les noms qui correspondent uniquement si le mois correspond aussi? IE Joe avril devrait être un seul ...
( @ Réponse de Abdul Il suffit de répondre à HAVING COUNT(*) > 1
La requête Shold ressemble à ceci maintenant
SELECT COUNT(*), col1 , col2 FROM test GROUP BY col1,col2 HAVING COUNT(*) > 1;
Voici l'exécution de celui-ci:
mysql> create table test(col1 varchar(20),col2 varchar(20));
Query OK, 0 rows affected (0.33 sec)
mysql> INSERT INTO test VALUES('Joe','April'),('Fred','May'),
-> ('Sam','April'),('Joe','April'),('Mark','Jan'),('Joe','Dec');
Query OK, 6 rows affected (0.06 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> SELECT COUNT(*), col1 , col2 FROM test GROUP BY col1,col2 HAVING COUNT(*) > 1;
+----------+------+-------+
| COUNT(*) | col1 | col2 |
+----------+------+-------+
| 2 | Joe | April |
+----------+------+-------+
1 row in set (0.24 sec)
mysql>
Si vous ne vous souciez pas du compte, retirez-le de la clause SELECT
mysql> SELECT col1 , col2 FROM test GROUP BY col1,col2 HAVING COUNT(*) > 1;
+------+-------+
| col1 | col2 |
+------+-------+
| Joe | April |
+------+-------+
1 row in set (0.00 sec)
mysql>
Créer une table et insérer des enregistrements
create table test(col1 varchar(20),col2 varchar(20));
INSERT INTO test VALUES('Joe','April'),('Fred','May'),('Sam','April'),('Joe','April'),('Mark','Jan'),('Joe','Dec');
SELECT * FROM test;
+------+-------+
| col1 | col2 |
+------+-------+
| Joe | April |
| Fred | May |
| Sam | April |
| Joe | April |
| Mark | Jan |
| Joe | Dec |
+------+-------+
6 rows in set (0.00 sec)
Trouvez le résultat réel
SELECT COUNT(*), col1 , col2 FROM test GROUP BY col1,col2;
+----------+------+-------+
| COUNT(*) | col1 | col2 |
+----------+------+-------+
| 1 | Fred | May |
| 2 | Joe | April |
| 1 | Joe | Dec |
| 1 | Mark | Jan |
| 1 | Sam | April |
+----------+------+-------+
5 rows in set (0.00 sec)