简体   繁体   中英

Sum quantities from different tables

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     |
+---------+-------------+----------+

Donation = what is given to the institution.
Beneficiation = institution gives to people in need.
I need to achieve "Table expected". I tried sum . I don't have much knowledge in SQL, it would be great if someone could help.

try adding the SUMs of both together

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

Something like this...

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 

You cannot simply use a JOIN on these tables because there is a 1:N relationship here. If you used a JOIN you would get row duplication and invalid results.

Instead you can have a sub-query bring in the vale from the two linked tables like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM