表A(字段名:userid):
aaa
bbb
ccc
表B(字段名:userid,code,val):
aaa,x1,1
aaa,x2,2
aaa,x2,3
bbb,x1,1
bbb,x2,2
查询结果(字段名:userid,x1,x2):
aaa,1,5
bbb,1,2
ccc,0,0
在用下列脚本实现查询结果时,发现始终缺少ccc
select A.userid userid,
sum(decode(B.code,'x1',B.x2,0)) x1,
sum(depcde(B.code,'x2',B.x2,0)) x2
from A,B where A.userid=B.userid(+)
order by A.userid
----------
aaa,1,5
bbb,1,2
貌似左关联没起作用,请问这个问题如何解决?
------解决方案--------------------
- SQL code
SQL> create table A( 2 userid varchar2(3) 3 );表已创建。SQL> insert into A values('aaa');已创建 1 行。SQL> insert into A values('bbb');已创建 1 行。SQL> insert into A values('ccc');已创建 1 行。SQL> create table B( 2 userid varchar2(3), 3 code varchar2(2), 4 val int 5 );表已创建。SQL> insert into B values('aaa','x1',1);已创建 1 行。SQL> insert into B values('aaa','x2',2);已创建 1 行。SQL> insert into B values('aaa','x2',3);已创建 1 行。SQL> insert into B values('bbb','x1',1);已创建 1 行。SQL> insert into B values('bbb','x2',2);已创建 1 行。SQL> select 2 A.userid, 3 sum(decode(B.code,'x1',B.val,0)) x1, 4 sum(decode(B.code,'x2',B.val,0)) x2 5 from A 6 left join B on A.userid=B.userid 7 group by A.userid;USERID X1 X2 ------ ---------- ---------- aaa 1 5 bbb 1 2 ccc 0 0