먼저 테이블을 생성하겠습니다 -
mysql> create table DemoTable1485 -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20), -> StudentSubject varchar(20) -> ); Query OK, 0 rows affected (0.72 sec)
삽입 명령을 사용하여 테이블에 일부 레코드 삽입 -
mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Chris','MySQL'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Robert','MongoDB'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Robert','MongoDB'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Chris','Java'); Query OK, 1 row affected (0.12 sec)
select 문을 사용하여 테이블의 모든 레코드 표시 -
mysql> select * from DemoTable1485;
이것은 다음과 같은 출력을 생성합니다 -
+-----------+-------------+----------------+ | StudentId | StudentName | StudentSubject | +-----------+-------------+----------------+ | 1 | Chris | MySQL | | 2 | Robert | MongoDB | | 3 | Robert | MongoDB | | 4 | Chris | Java | +-----------+-------------+----------------+ 4 rows in set (0.00 sec)
다음은 조건에 따라 값을 계산하는 쿼리입니다. -
mysql> select StudentSubject, -> sum(case when StudentName = 'Chris' THEN 1 ELSE 0 END) Chris_Count, -> sum(case when StudentName = 'Robert' THEN 1 ELSE 0 END) Robert_Count -> from DemoTable1485 -> group by StudentSubject;
이것은 다음과 같은 출력을 생성합니다 -
+----------------+-------------+--------------+ | StudentSubject | Chris_Count | Robert_Count | +----------------+-------------+--------------+ | MySQL | 1 | 0 | | MongoDB | 0 | 2 | | Java | 1 | 0 | +----------------+-------------+--------------+ 3 rows in set (0.00 sec)