主表:a
id name did(部门id)
101 test1 1
102 test2 2
103 test3 1附表:b (a表id每个月都有一条数据)
aid date month value
101 2011-1-1 1 111
101 2011-2-1 2 222
102 2011-1-1 1 1212
102 2011-2-1 2 2121
103 2011-1-1 1 1313
103 2011-2-1 2 2323我现在要查询所有部门id为1的数据,并且时间范围从2011年1月到2011年5月,但是现在库里只有1月和2月的数据,所以我查询出来的结果也是只有1月和2月的数据,但是我想要的结果是,1-5月的数据都有,如果该月的数据在数据库中没有用空或0代替,如下:
101 test1 2011-1-1 1 111
101 test1 2011-2-1 2 222
101 test1 2011-3-1 3 0
101 test1 2011-4-1 4 0
101 test1 2011-5-1 5 0
103 test3 2011-1-1 1 1313
103 test3 2011-2-1 2 2323
103 test3 2011-3-1 3 0
103 test3 2011-4-1 4 0
103 test3 2011-5-1 5 0我目前想到的方法是,用时间来循环,一个个查,但是貌似这样相率不高,so~ 求方法更好、效率更高的写法,还请各位帮忙!
我写的是存储过程,
id name did(部门id)
101 test1 1
102 test2 2
103 test3 1附表:b (a表id每个月都有一条数据)
aid date month value
101 2011-1-1 1 111
101 2011-2-1 2 222
102 2011-1-1 1 1212
102 2011-2-1 2 2121
103 2011-1-1 1 1313
103 2011-2-1 2 2323我现在要查询所有部门id为1的数据,并且时间范围从2011年1月到2011年5月,但是现在库里只有1月和2月的数据,所以我查询出来的结果也是只有1月和2月的数据,但是我想要的结果是,1-5月的数据都有,如果该月的数据在数据库中没有用空或0代替,如下:
101 test1 2011-1-1 1 111
101 test1 2011-2-1 2 222
101 test1 2011-3-1 3 0
101 test1 2011-4-1 4 0
101 test1 2011-5-1 5 0
103 test3 2011-1-1 1 1313
103 test3 2011-2-1 2 2323
103 test3 2011-3-1 3 0
103 test3 2011-4-1 4 0
103 test3 2011-5-1 5 0我目前想到的方法是,用时间来循环,一个个查,但是貌似这样相率不高,so~ 求方法更好、效率更高的写法,还请各位帮忙!
我写的是存储过程,
create table w_testA(
id number,
name varchar2(20),
did number
);insert into w_testA values(101,'test1',1);
insert into w_testA values(102,'test2',2);
insert into w_testA values(103,'test3',1);create table w_testB(
aid number,
"date" varchar2(10),
month number,
value number
);insert into w_testB values(101,'2011-1-1',1,111 );
insert into w_testB values(101,'2011-2-1',2,222 );
insert into w_testB values(102,'2011-1-1',1,1212);
insert into w_testB values(102,'2011-2-1',2,2121);
insert into w_testB values(103,'2011-1-1',1,1313);
insert into w_testB values(103,'2011-2-1',2,2323);commit;--开始查询
select a.id,a.name,t.dd,t.mm,nvl(b.value,0) value from (
select rownum mm,'2011-'||rownum||'-1' dd from user_objects where rownum<=5
) t cross join w_testA a
left join w_testB b on (t.mm=b.month and a.id=b.aid)
where a.did=1
order by a.id,t.mm;/*
ID NAME DD MM VALUE
101 test1 2011-1-1 1 111
101 test1 2011-2-1 2 222
101 test1 2011-3-1 3 0
101 test1 2011-4-1 4 0
101 test1 2011-5-1 5 0
103 test3 2011-1-1 1 1313
103 test3 2011-2-1 2 2323
103 test3 2011-3-1 3 0
103 test3 2011-4-1 4 0
103 test3 2011-5-1 5 0
*/--结束查询
drop table w_testA;
drop table w_testB;