I am trying to group rows on a postgres query. I have one row of data that has a field with a line number in it. The next 3 rows are null. I want to set them to the same value as the first row. Then the 5th row repeats the process. There may be 1 or more rows with null as the line number.
Here is a sample of the data with a simple query to pull the rows I want, ordered by line_num:
item_id | ordered_qty | unit | line_num | group_line_num | code |
---|---|---|---|---|---|
NP4484140T | 11 | PST^ | 7 | 7 | |
COL48LPT | 6 | PST | 8 | null | NP4484140T |
COL48EPT | 4 | PST | 9 | null | NP4484140T |
COL48BPT | 1 | PST | 10 | null | NP4484140T |
VP5578135T | 1 | PST^ | 52 | 52 | |
ONTP48CPT | 1 | PST | 53 | null | VP5578135T |
I want group_line_num to be 7 where it is null in the first set and 52 on the 4th null. The groups can also be created based on where the unit changes with the PST^ being the defining line of the group. I have tried using lag but since the number of null lines is variable I am not sure how to make it work.
2
Answers
Although it is possible to solve this with window functions it is not entirely straightforward and I think that the simplest solution is to self join the previous rows and identify the row with the highest value of group_line_num which can be used to replace a null value in the current row.
The described results can be easily achieved using
MAX
as a window function.The following code establishes a table of example values:
To determine the
group_line_num
using it’s most recent non-NULL value, run the following:The following query derives
group_line_num
from the most recentline_num
associated withunit = 'PST^'
:The two queries return identical results: