我有3张桌子。
表1
|Obj_id|Obj_Name|
----------------
|A | AAA|
|B | BBB|
|C | CCC|
表2
|Obj_id|Amount1|
----------------
|A | 1000|
|C | 20|
|A | 100|
|B | 50|
|C | 10|
表3
|Obj_id|Amount2|
----------------
|B | 500|
|C | 10|
|C | 40|
现在我需要创建一个程序“report”,它返回一个如下所示的光标
报告
|Obj_Name|Amount1|Amount2|Obj_id|
---------------------------------
|AAA | 1100| 0|A |
|BBB | 50| 500|B |
|CCC | 30| 50|C |
我用谷歌搜索,但没有匹配的答案。
答案 0 :(得分:1)
试试这个
SELECT
T1.Obj_Name
,NVL(T2.Amount1,0) AS Amount1
,NVL(T3.Amount2,0) AS Amount2
,NVL(T1.Obj_id ,0) AS Obj_id
FROM Table1 T1
LEFT JOIN Table2 T2 ON T1.Obj_id = T2.Obj_id
LEFT JOIN Table3 T3 ON T1.Obj_id = T3.Obj_id
ORDER BY T1.Obj_Name
<强>输出强>
Obj_Name Amount1 Amount2 Obj_id
AAA 1000 0 A
BBB 0 500 B
CCC 20 10 C
修改强>
SELECT
T1.Obj_Name AS Obj_Name
,NVL(T2.Amount1,0) AS Amount1
,NVL(T3.Amount2,0) AS Amount2
,T1.Obj_id AS Obj_id
FROM Table1 T1
LEFT JOIN (SELECT Obj_id,SUM(Amount1) AS Amount1 FROM Table2 GROUP BY Obj_id) T2 ON T1.Obj_id = T2.Obj_id
LEFT JOIN (SELECT Obj_id,SUM(Amount2) AS Amount2 FROM Table3 GROUP BY Obj_id) T3 ON T1.Obj_id = T3.Obj_id
ORDER BY T1.Obj_Name;
<强>输出强>
OBJ_NAME AMOUNT1 AMOUNT2 OBJ_ID
AAA 1100 0 A
BBB 50 500 B
CCC 30 50 C