이를 위해 GROUP BY와 함께 집계 함수 COUNT()를 사용합니다. 먼저 테이블을 생성하겠습니다 -
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value int ); Query OK, 0 rows affected (0.74 sec)
삽입 명령을 사용하여 테이블에 일부 레코드 삽입 -
mysql> insert into DemoTable(Value) values(976); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Value) values(67); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(Value) values(67); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Value) values(1); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable(Value) values(90); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(Value) values(1); Query OK, 1 row affected (0.41 sec) mysql> insert into DemoTable(Value) values(67); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(Value) values(976); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Value) values(90); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Value) values(1); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(Value) values(10); Query OK, 1 row affected (0.09 sec)
select 문을 사용하여 테이블의 모든 레코드 표시 -
mysql> select *from DemoTable;
출력
+----+-------+ | Id | Value | +----+-------+ | 1 | 976 | | 2 | 67 | | 3 | 67 | | 4 | 1 | | 5 | 90 | | 6 | 1 | | 7 | 67 | | 8 | 976 | | 9 | 90 | | 10 | 1 | | 11 | 10 | +----+-------+ 11 rows in set (0.00 sec)
다음은 MySQL에서 가장 자주 발생하는 값의 개수를 구하는 쿼리입니다 -
mysql> select Value,COUNT(Value) AS ValueFrequency from DemoTable group by Value order by ValueFrequency DESC;
출력
+-------+----------------+ | Value | ValueFrequency | +-------+----------------+ | 67 | 3 | | 1 | 3 | | 90 | 2 | | 976 | 2 | | 10 | 1 | +-------+----------------+ 5 rows in set (0.09 sec)