如何使用MySQL从同一列中选择不同的值并将它们显示在不同的列中?

如何使用MySQL从同一列中选择不同的值并将它们显示在不同的列中?

使用CASE语句基于条件选择不同的值。让我们首先创建一个表 –

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)

使用插入命令在表中插入一些记录 –

mysql> insert into DemoTable(Name,Score) values('Chris',45);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(Name,Score) values('David',68);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Name,Score) values('Robert',89);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Name,Score) values('Bob',34);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Name,Score) values('Sam',66);
Query OK, 1 row affected (0.22 sec)

使用select语句从表中显示所有记录 –

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)

以下是从同一列选择不同值的查询 –

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;

这将生成以下输出 –

+-------+--------------------+--------------------------+-----------------------+
| 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)

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程