The table look like this
number day amount
013xxxxxxxx 1 62773
013xxxxxxxx 8 52963
013xxxxxxxx 9 10810
013xxxxxxxx 10 84193
013xxxxxxxx 11 91791
019xxxxxxxx 1 89055
019xxxxxxxx 3 85366
019xxxxxxxx 5 47318
- In the above table. It is source table. Here we can see all the day number is not available. So I need to add those unavailable rows with amount 0.
I want the table like this.
number day amount
013xxxxxxxx 1 62773
013xxxxxxxx 2 0
013xxxxxxxx 3 0
013xxxxxxxx 4 0
013xxxxxxxx 5 0
013xxxxxxxx 6 0
013xxxxxxxx 7 0
013xxxxxxxx 8 52963
013xxxxxxxx 9 10810
013xxxxxxxx 10 84193
013xxxxxxxx 11 91791
019xxxxxxxx 1 89055
019xxxxxxxx 2 0
019xxxxxxxx 3 85366
019xxxxxxxx 4 0
019xxxxxxxx 5 47318
>Solution :
You can write this query (Result here)
with x as (SELECT distinct test.number,generated_day FROM generate_series(1, 31) as generated_day, test),
y as (SELECT distinct test.number, MAX(day) OVER (PARTITION BY number) AS max_day FROM test)
select x.number,x.generated_day,coalesce(t.amount,0)
from x left join test t on t."number" = x.number and t.day = x.generated_day
where x.generated_day <= (SELECT MAX(day) max_day FROM test where test.number = x.number)
order by 1, 2