包含2列的原始数据:
0 33
2 null
0 44
2 null
2 null
2 null
0 55
2 null
2 null
.....
我想要的结果:
2 33
2 44
2 44
2 44
2 55
2 55
....
我可以使用SQL语句来完成此任务吗? (返回仅包含2的行,但填充的值来自前一行的0),可能有许多' 2 null'在0之间。
答案 0 :(得分:0)
这样
with s as (
select *
from
(values
(1,0,33 ),
(2,2,null),
(3,0,44 ),
(4,2,null),
(5,2,null),
(6,2,null),
(7,0,55 ),
(8,2,null),
(9,2,null)
) T(id,a,b)
)
select s1.a, t.b
from s s1
cross apply (
select top(1) s2.b
from s s2
where s2.id < s1.id and s2.b is not null and s2.a = 0
order by s2.id desc ) t
where s1.a = 2
order by s1.id;
我使用CROSS APPLY,因此可以轻松扩展查询以从相关的&#39; 0&#39;中获取其他列。行。
答案 1 :(得分:0)
首先,为每行选择值为null:
SELECT col2 FROM (SELECT MAX(ID) FROM your_tbl t WHERE t.ID < ID AND col2 IS NOT NULL);
然后使用该子查询为您的表写一个条件:
SELECT col1, (
SELECT col2 FROM your_tbl where id = (SELECT MAX(ID) FROM your_tbl t
WHERE t.ID < tbl.ID AND col2 IS NOT NULL))
FROM your_tbl tbl WHERE col1 <> 0;