首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > oracle >

SQL貌似简单 小弟我写不出来

2013-12-30 
SQL貌似简单 我写不出来表a两列:startend20132016表b两列:yearmoney20131000201420002015300020164000b表

SQL貌似简单 我写不出来
表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

怎么办?
[解决办法]
建个中间表:

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
20130
20140
20151000
20160
20170
20183000
20194000
20200
[解决办法]

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
-------------------------
120131000
220142000
320150
420163000
520170

热点排行