我有一个包含四列的表格,我需要对其进行连接。其中两列包含一些 NULL 值。
我需要结果包含指示所有四列的分隔符,如下所示:
colA,colB,colC,colD
或者如果一列(此处为 colB)为空,
colA,,colC,colD
我似乎找不到一个干净的方法来做到这一点。我想到的最好的是:
concat_ws(colA, COALESCE(colB, ''), COALESCE(colC, ''), colD, ',')
这感觉很麻烦(尤其是因为我需要反复这样做)。有没有更好的办法?
最佳答案
由于最终值不能为 NULL,因此您无需担心保留它们。只需使用一个空字符串。这就是您在标准 SQL 中的编写方式。
select coalesce(cola, '') || ', ' ||
coalesce(colb, '') || ', ' ||
coalesce(colc, '') || ', ' ||
coalesce(cold, '')
from your_table_name;
concat_ws() 函数不会跳过空字符串,但它会 跳过空列。这意味着您仍然必须使用 coalesce()。
select concat_ws(', ', coalesce(cola, ''),
coalesce(colb, ''),
coalesce(colc, ''),
coalesce(colb, ''))
from your_table_name;
关于postgresql - Postgres : Concat multiple columns, 同时包含空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27862974/