Kỹ thuật
Sử dụng biểu thức CASE WHEN trong mệnh đề SELECT để tạo các cột điều kiện dựa trên giá trị của cột gốc.
1. Tạo bảng
mysql> create table DemoTable (
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name varchar(40),
Score int
);
Query OK, 0 rows affected (0.54 sec)
2. Chèn dữ liệu
mysql> insert into DemoTable(Name,Score) values('Chris',45);
mysql> insert into DemoTable(Name,Score) values('David',68);
mysql> insert into DemoTable(Name,Score) values('Robert',89);
mysql> insert into DemoTable(Name,Score) values('Bob',34);
mysql> insert into DemoTable(Name,Score) values('Sam',66);
3. Xem dữ liệu
mysql> select * from DemoTable;
+----+--------+-------+ | Id | Name | Score | +----+--------+-------+ | 1 | Chris | 45 | | 2 | David | 68 | | 3 | Robert | 89 | | 4 | Bob | 34 | | 5 | Sam | 66 | +----+--------+-------+ 5 rows in set (0.00 sec)
4. Truy vấn CASE WHEN tạo cột điều kiện
mysql> select Score,
case when Score < 40 then Score end as 'Score Less than 40',
case when Score between 60 and 70 then Score end as 'Score Between 60 and 70',
case when Score > 80 then Score end as 'Score greater than 80'
from DemoTable;
Kết quả:
+-------+--------------------+--------------------------+-----------------------+ | Score | Score Less than 40 | Score Between 60 and 70 | Score greater than 80 | +-------+--------------------+--------------------------+-----------------------+ | 45 | NULL | NULL | NULL | | 68 | NULL | 68 | NULL | | 89 | NULL | NULL | 89 | | 34 | 34 | NULL | NULL | | 66 | NULL | 66 | NULL | +-------+--------------------+--------------------------+-----------------------+ 5 rows in set, 1 warning (0.03 sec)
Ứng dụng: Phân loại dữ liệu theo ngưỡng để báo cáo, biểu đồ.