1

I am selecting data from multiple tables and want to insert data for missing years. Can I do this by using PLSQL or SQL ?

For example, below is output of my query:

YEAR  COUNT
----- -----
2012      5
2013      6
2015      2
2016      1
2019      0

I want to add the year and count=0 for missing years and finally I should have this -

YEAR  COUNT
----- -----
2012      5
2013      6
2014      0
2015      2
2016      1
2017      0
2018      0
2019      0
3
  • Sample data would help a lot. Commented Dec 11, 2019 at 22:09
  • Wait a minute. How did you get [2019, 0] but not 2014? Could you post your original query? Commented Dec 11, 2019 at 22:13
  • Hey Gen, Good question. The developer was able to insert current year count as 0 if missing. So that's why you see [2019,0]. The original query is very complex and long and will not be helpful. So I created a simple prototype using just two columns. Commented Dec 13, 2019 at 19:39

2 Answers 2

1

One option would be using connect by level <= .. syntax containing a left join with min(..) over (partition by ..) and max(..) over (partition by ..) analytic functions as quxiliary :

with t as
(
 select t0.*, 
        min(year) over (partition by 1) as min_year,
        max(year) over (partition by 1) as max_year
   from t0
)
select t1.year as "year", nvl( t."count" , 0) as "count"
  from
  (
   select distinct level + t.min_year - 1 as year
     from t
   connect by level <= t.max_year - t.min_year + 1 ) t1
  left join t
    on t.year = t1.year
 order by "year"

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks much!!!! This is exactly what I was looking for. Works for me without creating any new tables.
1

Create a table years including the year values.

Create table years ( year int)
insert into years values (2010),(2011),(2012), ... etc

Then all you need to use is left join like below:

SELECT y.year,ISNULL(t.val,0)
FROM years y
LEFT OUTER JOIN yourtable t ON t.year=y.year
ORDER BY y.year

1 Comment

Thank you!! this seems like a good solution.. But wont completely help me because of few limitations. 1.)I can only read data from this database so I can't create the years table. 2) Every time the output is going to contain different years and I want to insert year and count after the least minimum year. So for this example above, I want the results only from 2012. And in another case if the min year is 2015, then I want the results only from 2015.

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.