简体   繁体   中英

Wrong Result With Sum Function When Use Inner Join In SQL Server

i have two Tables;

Human
-----------
id
Name
list<car> cars
Car
-----------
id
name
price
Human

I want the total price of a human cars,so i used this SQL code for this:

SELECT
SUM(Price)
FROM Cars
INNER JOIN Humans ON Cars.Human_id = 1

but result is wrong.

for example:

id name Price Human_id
1 car1 10000 1
2 car2 15000 1

When I use that code for this table, the result is 50,000, But the answer must be 25.000. It seems that this mistake has something to do with the number of registered cars? can you explain why this wrong happen with sum function and inner join and calculate numbers multiple?

SELECT
SUM(Price)
FROM Cars
INNER JOIN Humans ON Cars.Human_id = 1

This a cartesian product between all Humans and Human 1's cars.

You probably want

SELECT
SUM(Price)
FROM Cars
INNER JOIN Humans 
 ON Cars.Human_id = Human.Id 
WHERE Human.Id = 1

SELECT SUM(Price) FROM Cars WHERE Cars.Human_id = 1

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