Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the next non-zero value in table partitioned by id?

Here is a subset of my table:

id date value
1 01/01/2022 5
1 02/02/2022 0
1 03/01/2022 0
1 04/02/2022 10
2 01/04/2022 5
2 02/04/2022 3
2 03/04/2022 0
2 04/04/2022 10

Where there are 0s in the value field, i would like to replace them with the non-zero value that occurs after the sequence of 0s are over, partitioned by id.

I have tried to use LAG but im really struggling as it takes the value above the current value in the table.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help will be appreciated.

Transformed table to look like

id date value
1 01/01/2022 5
1 02/02/2022 10
1 03/01/2022 10
1 04/02/2022 10
2 01/04/2022 5
2 02/04/2022 3
2 03/04/2022 10
2 04/04/2022 10

>Solution :

We group every 0 with the first value after it that’s not 0 and then we use max() over() to replace the 0s in the group.

select   id
        ,date
        ,max(value) over(partition by id, grp) as value
from
(
select   *
        ,count(case when value != 0 then 1 end) over(partition by id order by date desc) as grp
from     t
) t
order by id, date
id date value
1 2022-01-01 5
1 2022-02-02 10
1 2022-03-01 10
1 2022-04-02 10
2 2022-01-04 5
2 2022-02-04 3
2 2022-03-04 10
2 2022-04-04 10

Fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading