계산하려면 집계 함수 SUM()을 사용하고 조건으로 계산하려면 WHERE로 조건을 설정해야 합니다. 먼저 테이블을 생성하겠습니다 -
mysql> create table DemoTable1515 -> ( -> ClientId varchar(10), -> ClientName varchar(20) -> ); Query OK, 0 rows affected (0.53 sec)
삽입 명령을 사용하여 테이블에 일부 레코드 삽입 -
mysql> insert into DemoTable1515 values('CLI-101','Chris'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1515 values('CLI-110','David'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1515 values('CLI-101','Bob'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1515 values('CLI-101','Sam'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1515 values('CLI-101','Sam'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1515 values('CLI-101','Mike'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1515 values('CLI-130','Mike'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1515 values('CLI-101','Chris'); Query OK, 1 row affected (0.35 sec) mysql> insert into DemoTable1515 values('CLI-101','Sam'); Query OK, 1 row affected (0.18 sec)
select 문을 사용하여 테이블의 모든 레코드 표시 -
mysql> select * from DemoTable1515;
이것은 다음과 같은 출력을 생성합니다 -
+----------+------------+ | ClientId | ClientName | +----------+------------+ | CLI-101 | Chris | | CLI-110 | David | | CLI-101 | Bob | | CLI-101 | Sam | | CLI-101 | Sam | | CLI-101 | Mike | | CLI-130 | Mike | | CLI-101 | Chris | | CLI-101 | Sam | +----------+------------+ 9 rows in set (0.00 sec)
다음은 조건으로 계산하는 쿼리입니다 -
mysql> select ClientId,sum(ClientName='Sam') as NameOn101Id,count(*) as TotalNameOn101 from DemoTable1515 -> where ClientId='CLI-101';
이것은 다음과 같은 출력을 생성합니다 -
+----------+-------------+----------------+ | ClientId | NameOn101Id | TotalNameOn101 | +----------+-------------+----------------+ | CLI-101 | 3 | 7 | +----------+-------------+----------------+ 1 row in set (0.00 sec)