postgresql - Postgres : Concat multiple columns, 同时包含空值

标签 postgresql

我有一个包含四列的表格,我需要对其进行连接。其中两列包含一些 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/

相关文章:

java - C3P0 托管连接池无法从其主要资源或工厂资源中获取资源

sql - 带有 MIN(date) 的查询在 20 小时内未完成 : should it be like that, 还是我做错了什么?

laravel - 在具有关系的 Laravel Eloquent 查询构建器中将 UNION 与 DISTINCT 结合使用

python - 无法在 postgresql sqlalchemy 中创建表

postgresql - PGAdmin4 : Can't prevent browser for opening - archlinux

postgresql - 如何在 postgresql 交叉表中用零替换空值

PostgreSQL 数据库存储过程

postgresql - 什么合适的锁定技术可以防止插入数据? [PostgreSQL]

oracle 存储过程 OUT 参数与 postgresql pl/pgsql 函数 OUT 参数

sql - 如何重组 postgres 表中的记录并永久保存