Oracle:游标过程:将2个表与join相加

时间:2013-08-08 08:53:29

标签: oracle stored-procedures join cursor sum

我有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     |

我用谷歌搜索,但没有匹配的答案。

1 个答案:

答案 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

SQL FIDDLE DEMO

<强>输出

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;

SQL FIDDLE DEMO UPDATED

<强>输出

OBJ_NAME AMOUNT1  AMOUNT2  OBJ_ID
AAA      1100       0      A
BBB      50         500    B
CCC      30         50     C