来自不同表的总和数量

时间:2015-07-28 18:32:27

标签: sql

ProdStock
+---------+--------------+
| ID_Prod |  Description |
+---------+--------------+
|    1    |    tshirt    |
|    2    |    pants     |
|    3    |      hat     |
+---------+--------------+

Donation
+---------+---------+----------+
| id_dona | ID_Prod | Quantity |
+---------+---------+----------+
|    1    |    1    |    10    |
|    2    |    2    |    20    |
|    3    |    1    |    30    |
|    4    |    3    |    5     |
+---------+---------+----------+

Beneficiation
+---------+---------+----------+ 
| id_bene | ID_Prod | Quantity |
+---------+---------+----------+
|    1    |    1    |   -5     |
|    2    |    2    |   -10    |
|    3    |    1    |   -15    |
+---------+---------+----------+

Table expected
+---------+-------------+----------+
| ID_Prod | Description | Quantity |
+---------+-------------+----------+
|    1    |    tshirt   |    20    |
|    2    |    pants    |    10    |
|    3    |      hat    |    5     |
+---------+-------------+----------+

捐赠=给予该机构的内容 选矿=机构给予有需要的人。
我需要实现" Table expected"。我试过了sum。我对SQL没有太多的了解,如果有人可以提供帮助,那就太好了。

3 个答案:

答案 0 :(得分:3)

尝试将两者的SUM加在一起

SELECT  p.ID_Prod,
        Description,
        ISNULL(d.Quantity,0) + ISNULL(b.Quantity,0) AS Quantity
FROM    ProdStock p
        LEFT OUTER JOIN (SELECT ID_Prod, 
                                SUM(Quantity) Quantity 
                         FROM   Donation 
                         GROUP BY ID_Prod) d ON p.ID_Prod = d.ID_Prod
        LEFT OUTER JOIN (SELECT ID_Prod, 
                                SUM(Quantity) Quantity 
                         FROM Beneficiation 
                         GROUP BY ID_Prod) b ON p.ID_Prod = b.ID_Prod

答案 1 :(得分:0)

像这样......

SELECT  ps.ID_Prod,
                ps.Description,
                SUM(d.Quantity) + SUM(b.Quantity) AS Quantity
FROM ProdStock ps
            INNER JOIN Donation d ON ps.ID_Prod = d.ID_Prod
            INNER JOIN Beneficiation b ON d.ID_Prod = b.ID_Prod
GROUP BY ps.ID_Prod, ps.Description 

答案 2 :(得分:0)

您不能在这些表格上使用JOIN,因为此处存在1:N关系。如果您使用JOIN,则会出现行重复和无效结果。

相反,您可以使用子查询从两个链接表中引入该值:

SELECT  ID_Prod,
        Description,
        (ISNULL((SELECT SUM(Quantity) FROM Donation d WHERE p.ID_Prod = d.ID_Prod), 0) + 
        ISNULL((SELECT SUM(Quantity) FROM Beneficiation b WHERE p.ID_Prod = b.ID_Prod), 0)) AS Quantity
FROM    ProdStock p