日期:2014-05-17  浏览次数:20809 次

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
2013 0
2014 0
2015 1000
2016 0
2017 0
2018 3000
2019 4000
2020 0
------解决方案--------------------

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