This is my sql query:
select
sum(table1.quantity) as t1q,
sum(table1_2.quantity) as t2q,
sum(table3.quantity) as t3q,
table1.pid as pid
from table1
inner join table3 on table1.pid=table3.pid
inner join table1 table1_2 on table1.pid=table1_2.pid
where
table1.to_id=10 and
table3.some_id=10 and
table1_2.from_id=10
group by pid;
Sample Data:
Table1:
quantity, to_id, from_id, pid
6, 10, 999999, 345
4, 888999, 10, 345
3, 888999, 10, 345
If you observer above sql:
There are 2 tables:
Table1 (same table used twice as table1 and table1_2)
Table3
I want to fetch from table1.to_id=10 for calculating t1q and table1(same table).from_id=10 for calculating t2q.
I am getting correct output in some cases but in some cases, t1q is giving value as 12 when it should be 6. In that scenario, its because after joins, there are 2 records of table1_2 and only one record for for table1. So, it is counting table1.quantity twice even though its has only one record after filtering.
Can you please provide correct sql query.
from_id = 10. Is there some other field in table1 that you can use in your where clause to restrict the results to only returning one record from inner join operation?