我有一个包含大量值列的表,如下所示:
CREATE TABLE tbl ("timestamp" timestamp PRIMARY KEY, "a" real, "b" real, "c" real)
该表可能包含动态数量的值列(如 a、b、c)。
我需要删除所有值为空但时间戳不为空的行。
我无法构建只返回空行的选择查询。
做类似的事情:
select *
from tbl
where tbl is null
不会工作,因为时间戳不为空
我尝试采用以下工作示例:
select *
from tbl
where not (a,b,c) is null
并向其添加子选择:
select *
from tbl
where not (
SELECT string_agg(column_name, ',')
FROM information_schema.columns
WHERE table_name = 'tbl' and column_name != 'timestamp'
) is null
但它不起作用。
最佳答案
您可以将该行转换为 JSONB 对象,删除“时间戳”列,然后检查空值:
select *
from tbl
where jsonb_strip_nulls(to_jsonb(tbl) - 'timestamp') = '{}'::jsonb;
这可以直接用于删除行:
delete from tbl
where jsonb_strip_nulls(to_jsonb(tbl) - 'timestamp') = '{}'::jsonb);
关于sql - 删除空行,其中列是动态选择的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52717285/