[英]How can I insert new rows into a query result using PL/SQL or SQL query in Oracle?
I am selecting data from multiple tables and want to insert data for missing years.我正在从多个表中选择数据并希望插入缺失年份的数据。 Can I do this by using PLSQL
or SQL
?我可以使用PLSQL
或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
添加year
和count=0
,最后我应该有这个 -
YEAR COUNT
----- -----
2012 5
2013 6
2014 0
2015 2
2016 1
2017 0
2018 0
2019 0
Create a table years
including the year values.创建一个表years
包括年度值。
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
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 :一种选择是使用connect by level <= ..
含有语法left join
用min(..) over (partition by ..)
和max(..) over (partition by ..)
解析函数作为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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.