简体   繁体   中英

Sum quantities from a second table in SQL

I have a table Owners :

Owner   product
-----------------
Jhon    product1
Jhon    product2
Jhon    product3
Chris   product4

Another table Products :

Product   QuantitySold
-----------------------
Product1      3
Product2      5
Product3      2
Product4      7

How do I write a SQL query to come up with the total number of unit sold per owner?

For example for Jhon I should get 10 (3+5+2)

I tried:

Select 
    Owners.owner, 
    sum(Products.quantitySold) 
from 
    Products, Owners
Group by 
    owners.owner

But that returns the total of quantitySold for any owner (17 = 3+5+2+7)

Thank you very much

You forgot the JOIN condition. Basically, you're doing a CROSS JOIN instead of an INNER/OUTER JOIN . My suggestion is not to use the old-style JOIN syntax and use explicit JOIN instead:

SELECT
    o.Owner,
    SUM(p.QuantitySold)
FROM Owners o
INNER JOIN Products p
    ON p.Product = o.Product
GROUP BY o.Owner

Reference:

You could also use this,

SELECT DISTINCT(A.Owner), SUM(B.QuantitySold) OVER(PARTITION BY A.Owner ORDER BY A.Owner)
FROM OWNERS A
INNER JOIN PRODUCTS B ON A.product = B.product

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