“携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第13天,点击查看活动详情
distinct coalesce()
coalesce():返回最后一个有值的函数。
对于Oracle数据库,一般经常对空值处理的函数为NVL,而mysql中常用到的是ifnull,这两个函数相似,其实都是由一个函数衍生而来,那就是COALESCE()函数。
COALESCE()函数 定义:返回列表中第一个非null表达式的值。如果所有表达式求值为null,则返回null
COALESCE()函数有两种用法:
1.COALESCE ( expression1, expression2 );
2.COALESCE ( expression1, expression2, ... expression-n );
其中第一种就相当于Oracle中的nvl或者mysql中的ifnull,写成表达式的形式为:
CASE WHEN expression1 IS NOT NULL THEN expression1 ELSE
expression2 END;
第二种可以包含n个表达式,表示如果第一个不为空取第一个,否则判断下一个,以此类推,如果全部为空,则返回null值。
需注意:vertica中空字符串跟null值不一样
当进行统计操作时DISTINCT的字段有null值解决办法:
select count(distinct coalesce(columnName)) from tableName
example:
mysql> select * from score;;
+----+------+-------+
| id | name | score |
+----+------+-------+
| 1 | a | 100 |
| 2 | b | 100 |
| 3 | c | 95 |
| 4 | d | 95 |
| 5 | e | 95 |
| 6 | a | 90 |
| 7 | a | 89 |
| 8 | NULL | 20 |
| 9 | NULL | 10 |
+----+------+-------+
9 rows in set (0.00 sec)
mysql> select count(distinct(name)) from score;
+-----------------------+
| count(distinct(name)) |
+-----------------------+
| 5 |
+-----------------------+
1 row in set (0.00 sec)
mysql> select count(distinct COALESCE(name,'null')) from score;
+---------------------------------------+
| count(distinct COALESCE(name,'null')) |
+---------------------------------------+
| 6 |
+---------------------------------------+
1 row in set (0.00 sec)
ISNULL、IFNULL
isnull(expr):
如果expr为null,那么isnull()的返回值为1,否则返回值为0.
ifnull(expr1,expr2):
假如expr1不为NULL,则IFNULL()的返回值为expr1,否则其返回值为expr2;
nullif(expr1,expr2):
如果expr1=expr2成立,那么返回null,否则返回expr1.
COALESCE和IFNULL函数的区别
当只有2个表达式的时候,两者的用法可以互换 ,当有多个参数判断是否null时,只能使用COALESCE。