如何查找和替换每行的第一个空值?

时间:2019-09-05 12:45:06

标签: sql postgresql isnull sql-null

我有一张桌子,桌子大约20列,超过5000行。对于每一行,我都尝试用字符串"end"替换第一个空值。

我所拥有的:

BEGIN TRANSACTION;

/* Create a table called dataframe */
CREATE TABLE dataframe(id integer primary key, col1 text, col2 text, col3 text, col4 text, col5 text);

/* Create few records in this table */
INSERT INTO dataframe VALUES(1,'a',null,null,null,null);
INSERT INTO dataframe VALUES(2,'a','b',null,null,null);
INSERT INTO dataframe VALUES(3,'a','c','d','e', null);
INSERT INTO dataframe VALUES(4,'a','c','d',null, null);
INSERT INTO dataframe VALUES(5,'a','c',null, null, null);
COMMIT;

/* Display all the records from the table */
SELECT * FROM dataframe;

我需要什么:

BEGIN TRANSACTION;

/* Create a table called dataframe */
CREATE TABLE dataframe(id integer primary key, col1 text, col2 text, col3 text, col4 text, col5 text);

/* Create few records in this table */
INSERT INTO dataframe VALUES(1,'a','end',null,null,null);
INSERT INTO dataframe VALUES(2,'a','b','end',null,null);
INSERT INTO dataframe VALUES(3,'a','c','d','e', 'end');
INSERT INTO dataframe VALUES(4,'a','c','d','end', null);
INSERT INTO dataframe VALUES(5,'a','c','end', null, null);
COMMIT;

/* Display all the records from the table */
SELECT * FROM dataframe;

我可以在行级使用FIRST_VALUE()吗?

1 个答案:

答案 0 :(得分:3)

多个case表达式可能是最简单的方法:

select df.id,
       (case when df.col1 is null
             then 'end' else df.col1
        end) as col1,
       (case when df.col1 is not null and df.col2 is null
             then 'end' else df.col2
        end) as col2,
       (case when df.col1 is not null and df.col2 is not null and df.col3 is null
             then 'end' else df.col3
        end) as col3,
       . . .
from dataframe df;

如果您想实际更改数据,则可以轻松地将其应用于update

相关问题