如何使用旧值替换为null

时间:2019-01-10 13:58:06

标签: sql sqlite

此表:

field5 field19
Dr        1
Null      2
Null      3
Td        4
Td        5
Null      6

表格应为以下形式:

 field5   field19
    Dr      1
    Dr      2
    Dr      3
    Td      4
    Td      5
    Td      6

我已经寻找了很长时间,但是对于sqlite,我没有找到解决方案。请帮助

2 个答案:

答案 0 :(得分:0)

窗口功能会有所帮助:

select *,  
      max(field5) over (order by field19)
from table t;

您还可以使用 correlated 子查询:

select t.*,
       (select t1.field5 
        from table t1 
        where t1.field19 <= t.field19 and t1.field5 is not null
        order by t1.field19 desc 
        limit 1
       )
from table t;

答案 1 :(得分:0)

您可以使用它来为null(如果存在)找到以前的 field5值:

select 
coalesce(t.field5, (
  select tt.field5 from tablename tt where tt.field19 = (
    select max(tablename.field19) from tablename where tablename.field19 < t.field19 and tablename.field5 is not null)
  )
) as field5, 
t.field19 
from tablename t

模式(SQLite v3.26)

CREATE TABLE tablename ( field5 TEXT, field19   INTEGER ); 
insert into tablename (field5, field19) values 
('Dr1', 1), 
(null, 2), (null, 3), 
('Td', 4), 
('Td', 5), (null, 6), (null, 7),('Dr1', 8),(null, 9),('Td', 10),(null, 11),(null, 12);

查询#1

select * from tablename;

| field5 | field19 |
| ------ | ------- |
| Dr1    | 1       |
|        | 2       |
|        | 3       |
| Td     | 4       |
| Td     | 5       |
|        | 6       |
|        | 7       |
| Dr1    | 8       |
|        | 9       |
| Td     | 10      |
|        | 11      |
|        | 12      |

查询#2

select 
coalesce(t.field5, (
  select tt.field5 from tablename tt where tt.field19 = (
    select max(tablename.field19) from tablename where tablename.field19 < t.field19 and tablename.field5 is not null)
  )
) as field5, 
t.field19 
from tablename t;

| field5 | field19 |
| ------ | ------- |
| Dr1    | 1       |
| Dr1    | 2       |
| Dr1    | 3       |
| Td     | 4       |
| Td     | 5       |
| Td     | 6       |
| Td     | 7       |
| Dr1    | 8       |
| Dr1    | 9       |
| Td     | 10      |
| Td     | 11      |
| Td     | 12      |

View on DB Fiddle