coalesce
返回参数列表中的第一个非空值。
此函数返回参数列表中的第一个非空值。该列表由元素组成,每个元素可以是常量值、数组、序列、时间或上述任何类型的表列。
coalesce( arg1, arg2, ... argN);
当需要结果但不知道字段值何时存在时,这可能会很有用。 例如,考虑一个名为 Person 的表,其中包含三种类型的联系人电话号码:Business_Phone(办公电话)、Cell_Phone(手机)和 Home_Phone(家庭电话)。 如果我们想为每个人获取一个联系号码,可以指定以下选择语句来提取第一个非空值:
select Name, coalesce( Business_Phone, Cell_Phone, Home_Phone) as Contact_Phone
from Person;
参数
arg1, arg2, ... argN
一个列表,其每个元素可以是常量值、数组、序列、时间或上述任何类型的表列。
示例
示例1
coalesce() 函数可用于如下简单的列表:
select coalesce( 1, 2, 3), coalesce( null, null, 3);
#1 #2
--------------------------------------------------------
1 3
示例2
或者它可以用于不同类型的表列。例如,考虑下面的表 t,用以下两行值进行初始化:
create table t(
i1 int, i2 int,
ch1 char(20), ch2 char(20),
sc1 sequence(char(5)), sc2 sequence(char(5)),
si1 sequence(int), si2 sequence(int),
a1 array(int), a2 array(int),
t1 time, t2 time,
d1 decimal(15,2), d2 decimal(15,2),
b1 boolean, b2 boolean
);
insert into t values(null, 1,
null, 'ch1',
null, ['1','2','3','4','5'],
null, [1,2,3,4,5],
null, [1,2,3,4,5,6,7,8,9,0],
null, '04-02-2019 10:19',
null, 10.2,
null, true);
insert into t values(2, null,
'ch2', null,
['a1','a2','a3','a4','a5'], null,
[11,12,13,14,15], null,
[10,20,30,40,50], null,
'04-02-2019 10:23', null,
10.02, null,
null, false);
以下的 SELECT 语句使用函数 COALESCE() 从每个指定的字段列表中提取第一个非空值(请注意,此处对 SELECT 结果进行了重新格式化,以便更易于查看它们与字段之间的关联):
select coalesce(i1, i2) as i,
coalesce(ch1, ch2) as ch,
coalesce(sc1, sc2) as sc,
coalesce(si1, si2) as si,
coalesce(a1, a2) as a,
coalesce(t1, t2) as t,
coalesce(d1, d2) as d,
coalesce(b1, b2) as b
from t order by i;
i
ch
sc
si
a
t
d
b
--------------------------------------------------------
1
ch1
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
04/02/2019 10:19:00
10.20
true
2
ch2
{a1, a2, a3, a4, a5}
{11, 12, 13, 14, 15}
[10, 20, 30, 40, 50]
04/02/2019 10:23:00
10.02
false
示例3
上述描述中所给出的实际示例可以使用如下定义并初始化的“Person”表:
create table Person( Name char(20), Business_Phone char(20),
Cell_Phone char(20), Home_Phone char(20));
insert into Person values( 'Hal', '888-555-9999', '888-555-1111', '888-555-3333');
insert into Person values( 'Barb', null, '888-555-2222', '888-555-4444');
insert into Person values( 'Doug', null, null, '888-555-5555');
select * from Person;
Name Business_Phone Cell_Phone Home_Phone
--------------------------------------------------------
Hal 888-555-9999 888-555-1111 888-555-3333
Barb null 888-555-2222 888-555-4444
Doug null null 888-555-5555
现在我们可以使用以下选择语句,按照以下规则为每个表行提取一个联系号码:
如果一个人有商务电话,就使用商务电话号码。
如果一个人没有办公电话但有手机,就用手机号码。
如果一个人没有商务电话,没有手机,但有固定电话,那就用固定电话号码。
select Name, coalesce( Business_Phone, Cell_Phone, Home_Phone) as Contact_Phone
from Person;
Name Contact_Phone
--------------------------------------------------------
Hal 888-555-9999
Barb 888-555-2222
Doug 888-555-5555