I have two tables:
1. Master
| ID | Name | Amount | |-----|--------|--------| | 1 | a | 5000 | | 2 | b | 10000 | | 3 | c | 5000 | | 4 | d | 8000 |
2. Detail
| ID |MasterID| PID | Qty | |-----|--------|-------|------| | 1 | 1 | 1 | 10 | | 2 | 1 | 2 | 20 | | 3 | 2 | 2 | 60 | | 4 | 2 | 3 | 10 | | 5 | 3 | 4 | 100 | | 6 | 4 | 1 | 20 | | 7 | 4 | 3 | 40 |
I want to select sum(Amount) from Master which joins to Deatil where Detail.PID in (1,2,3)
So I execute the following query:
SELECT SUM(Amount) FROM Master M INNER JOIN Detail D ON M.ID = D.MasterID WHERE D.PID IN (1,2,3)
Result should be 20000. But I am getting 40000
See this fiddle. Any suggestion?
You are getting exactly double the amount because the detail table has two occurences for each of the PIDs in the WHERE clause.
See demo
Use