SQL貌似简单 我写不出来

不啃不舒服斯基 2013-11-10 11:22:48
表a两列:
start end
2013 2016

表b两列:
year money
2013 1000
2014 2000
2015 3000
2016 4000

b表中的年份范围来自于a表,
我想查询出b表现在这样的结果,但是b表有时是没有数据的,这时我希望仍能查出这样的结果来:
2013 0
2014 0
2015 0
2016 0

怎么办?
...全文
248 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
jianhenjh 2013-11-19
  • 打赏
  • 举报
回复
  • 打赏
  • 举报
回复
会结贴的,请再稍等。
mawenpinga 2013-11-11
  • 打赏
  • 举报
回复
建个中间表:
create table table_91 (start_year number(4),end_year number(4));
insert into table_91 values('2013','2020');
create table table_92 (year number(4),count number(5));
insert into table_92 values('2015','1000');
insert into table_92 values('2018','3000');
insert into table_92 values('2019','4000');
create table table_93(year number(4),count number(6));

declare
start_year1 number(4):=0;
end_year1 number(4):=0;
m_count number(2);
begin
select start_year into start_year1 from table_91;
select end_year into end_year1 from table_91;
loop
select count(*) into m_count from table_92 where year =start_year1;
if m_count = 0 then 
insert into table_93 values(start_year1,0);
else 
insert into table_93 select * from table_92 where year =start_year1 ;
end if;
start_year1:=start_year1+1;
if start_year1 = end_year1+1 then
  exit;
end if;
end loop;
commit;
end;

select * from table_93;
YEAR COUNT 2013 0 2014 0 2015 1000 2016 0 2017 0 2018 3000 2019 4000 2020 0
大话EPM 2013-11-11
  • 打赏
  • 举报
回复
查不出来的就填充啊 用lag or lead分析函数
  • 打赏
  • 举报
回复
感谢,晚上结贴
  • 打赏
  • 举报
回复

with tableA as
(
     select 2013 c1,2017 c2 from dual
),tableB as
(
     select 2013 c3,1000 c4 from dual union all
     select 2014 c3,2000 c4 from dual union all
     select 2016 c3,3000 c4 from dual
)

select a.c1,nvl(b.c4,0) c4
from 
(
    select c1+level-1 c1
    from tableA
    connect by level <= c2-c1+1
) a left join tableB b on a.c1 = b.c3
order by a.c1

     c1     c4
-------------------------
1	2013	1000
2	2014	2000
3	2015	0
4	2016	3000
5	2017	0

17,086

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧