联接3个表和SUM ORACLE

时间:2019-01-07 23:54:46

标签: oracle

我有3张桌子:

Product:
+----------------------------------------+
| ID_product | name_product |   Amount   |
+----------------------------------------+
|     0      |    Door      |    450     |
+----------------------------------------+
|     1      |    Fence     |    1500    |
+----------------------------------------+

Operation:
+----------------------------------------+
| ID_operation | name_operation |  cost  |
+----------------------------------------+
|      0       |     Repair     |   250  |
+----------------------------------------+
|      1       |     Build      |   320  |
+----------------------------------------+

Process:
+----------------------------------------+
|    ID_product   |    ID_operation      |
+----------------------------------------+
|       0         |          0           |
+----------------------------------------+
|       0         |          1           |
+----------------------------------------+
|       1         |          0           |
+----------------------------------------+
|       1         |          1           |
+----------------------------------------+
  

并且需要像这样计算每种产品的成本总和:

    Result table:
   +-----------------------------------+
   |  name_product  |    TOTAL_COSTS   |
   +-----------------------------------+
   |      Door      |   570 (250+320)  |
   +-----------------------------------+
   |      Fence     |        570       |
   +-----------------------------------+

但是我不知道如何。我想我需要像下面这样的JOINS,但我不知道如何处理总和。

SELECT name_product, operation.cost
FROM product
JOIN process ON product.ID_product = process.ID_product
JOIN operation ON operation.ID_operation = process.ID_operation
ORDER BY product.ID_product;

2 个答案:

答案 0 :(得分:1)

尝试以下Query

SELECT P.NAME_PRODUCT,SUM(O.COST)COST
FROM PROCESS PR,PRODUCT P,OPERATION O
WHERE PR.ID_PRODUCT=P.ID_PRODUCT
AND PR.ID_OPERATION=O.ID_OPERATION
GROUP BY P.NAME_PRODUCT;

答案 1 :(得分:0)

您快到了。您的JOIN没问题,您只需要添加带有聚合函数GROUP BY的{​​{1}}子句即可。

SUM