从具有空值和非空值的多列中获取最大值?
为此,您可以使用COALESCE()
。要获得最大值,请GREATEST()
在MySQL中使用。让我们首先创建一个表-
mysql> create table DemoTable-> (
-> Value1 int,
-> Value2 int,
-> Value3 int
-> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values(NULL,80,76);mysql> insert into DemoTable values(NULL,NULL,100);
mysql> insert into DemoTable values(56,NULL,45);
mysql> insert into DemoTable values(56,120,90);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+--------+--------+--------+| Value1 | Value2 | Value3 |
+--------+--------+--------+
| NULL | 80 | 76 |
| NULL | NULL | 100 |
| 56 | NULL | 45 |
| 56 | 120 | 90 |
+--------+--------+--------+
4 rows in set (0.00 sec)
以下是从多个列中获取最大值的查询-
mysql> select greatest(coalesce(Value1,0),coalesce(Value2,0),coalesce(Value3,0)) from DemoTable;
这将产生以下输出-
+--------------------------------------------------------------------+| greatest(coalesce(Value1,0),coalesce(Value2,0),coalesce(Value3,0)) |
+--------------------------------------------------------------------+
| 80 |
| 100 |
| 56 |
| 120 |
+--------------------------------------------------------------------+
4 rows in set (0.00 sec)
以上是 从具有空值和非空值的多列中获取最大值? 的全部内容, 来源链接: utcz.com/z/326993.html