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 can I get the target table in PostgreSQL?

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)

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

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
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