1

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
2
  • Why did you use the Oracle tag? Do you use PostgreSQL (as the title suggests), or both, or what? Commented Jan 17, 2022 at 9:10
  • my mistake,.... I have edited the post... I need for postgres only. Commented Jan 17, 2022 at 9:12

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot... It works like a champ....!!!
1

Using a calendar table approach:

WITH cte AS (
    SELECT number, MIN(day) AS min_day, MAX(day) AS max_day
    FROM yourTable
    GROUP BY number
)

SELECT n.number, s.day, COALESCE(t2.amount, 0) AS amount
FROM (SELECT DISTINCT number FROM yourTable) n
CROSS JOIN (SELECT * FROM generate_series(1, 31)) AS s(day)
INNER JOIN cte 
    ON t.number = n.number
LEFT JOIN yourTable t2
    ON t2.number = n.number AND t2.day = s.day
WHERE s.day BETWEEN t.min_day AND t.max_day
ORDER BY n.number, s.day;

screen capture from demo link below

Demo

2 Comments

SQL Error [42P01]: ERROR: missing FROM-clause entry for table "s"¶ Position: 324
@BackstreetImrul I fixed it, tough question, check the demo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.