고유한 값을 가져오고 계산하려면 GROUP BY 절을 사용할 수 있습니다.
구문은 다음과 같습니다.
select yourColumnName,count(*) as anyAliasName from yourTableName group by yourColumnName;
위의 구문을 이해하기 위해 테이블을 생성해 보겠습니다. 테이블 생성 쿼리는 다음과 같습니다.
mysql> create table GroupByAndCountDemo -> ( -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ClientName varchar(100) -> ); Query OK, 0 rows affected (0.64 sec)
삽입 명령을 사용하여 테이블에 일부 레코드를 삽입하십시오. 쿼리는 다음과 같습니다 -
mysql> insert into GroupByAndCountDemo(ClientName) values('John'); Query OK, 1 row affected (0.18 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('Sam'); Query OK, 1 row affected (0.15 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('Sam'); Query OK, 1 row affected (0.16 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('John'); Query OK, 1 row affected (0.51 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('John'); Query OK, 1 row affected (0.15 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('John'); Query OK, 1 row affected (0.13 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('Sam'); Query OK, 1 row affected (0.08 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('Sam'); Query OK, 1 row affected (0.47 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('Sam'); Query OK, 1 row affected (0.09 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('John'); Query OK, 1 row affected (0.13 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('John'); Query OK, 1 row affected (0.18 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('John'); Query OK, 1 row affected (0.10 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('David'); Query OK, 1 row affected (0.12 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('Maxwell'); Query OK, 1 row affected (0.17 sec) mysql> insert into GroupByAndCountDemo(ClientName) values('Maxwell'); Query OK, 1 row affected (0.15 sec)
select 문을 사용하여 테이블의 모든 레코드를 표시합니다. 쿼리는 다음과 같습니다 -
mysql> select *from GroupByAndCountDemo;
출력은 다음과 같습니다
+----------+------------+ | ClientId | ClientName | +----------+------------+ | 1 | John | | 2 | Carol | | 3 | Sam | | 4 | Sam | | 5 | John | | 6 | John | | 7 | John | | 8 | Sam | | 9 | Sam | | 10 | Sam | | 11 | John | | 12 | John | | 13 | John | | 14 | David | | 15 | Maxwell | | 16 | Maxwell | +----------+------------+ 16 rows in set (0.00 sec)
이제 다음 쿼리를 사용하여 고유한 값을 얻고 계산해 보겠습니다.
mysql> select ClientName,count(*) as TotalCount from GroupByAndCountDemo group by ClientName;
다음은 출력입니다.
+------------+------------+ | ClientName | TotalCount | +------------+------------+ | John | 7 | | Carol | 1 | | Sam | 5 | | David | 1 | | Maxwell | 2 | +------------+------------+ 5 rows in set (0.00 sec)