问题描述
在选择语句中,我有 max(array_to_string(v_date,'||'::text)) filter (where type_key=1)
列。
现在我必须使用 COALESCE 来显示 v_date
空值的默认值。
select obj_key,max(updated_on) as updated_on,max(att.status) as status,COALESCE(max(array_to_string(v_date,'||'::text)) filter (where att.type_key=1),max(default_value)) as "dob",max(array_to_string(v_text,'||'::text)) filter (where att.type_key=2) as "First Name",'||'::text)) filter (where att.type_key=3) as "Last Name",max(array_to_string(v_number,'||'::text)) filter (where att.type_key=4) as "Contact"
from attributes att right join types ty on att.type_key=ty.type_key
group by obj_key
obj_key 3 的 dob 必须是 '1/1/1950' 但它给出了 sample1 吗?
是否可以在coalesce中使用array_to_string来获取非空值(默认值)?
解决方法
您需要再次加入类型表以获取值,因为当您加入按 obj_key 分组的属性表时,您只有值 2 和 3 的 type_key 的 default_values。
试试这个版本:
select obj_key,max(updated_on) as updated_on,max(att.status) as status,COALESCE(max(array_to_string(v_date,'||'::text)) filter (where att.type_key=1),(select default_value from types where type_key=1)) as "DOB",COALESCE(max(array_to_string(v_text,'||'::text)) filter (where att.type_key=2),(select default_value from types where type_key=2)) as "First Name",'||'::text)) filter (where att.type_key=3),(select default_value from types where type_key=3))as "Last Name",COALESCE(max(array_to_string(v_number,'||'::text)) filter (where att.type_key=4),(select default_value from types where type_key=4)) as "Contact"
from attributes att right join types ty on att.type_key=ty.type_key
group by obj_key