Table : O
ID Date
1 2016-01-10
2 2016-01-10
3 2016-01-11
Table : OD
ODI ID Quantity
1 1 1
2 1 2
3 2 1
4 3 1
Table: OH
OHI ID
1 1
2 2
3 1
4 3
I have three table O,OD,OH. I need to join these three table and get the sum of quantity For each day.
Tried
SELECT O.date,SUM(od.Quantity),group_concat(OHI) FROM O
INNER JOIN OD ON OD.ID = O.ID
INNER JOIN OH ON OH.ID = O.ID
GROUP BY O.date;
But the resulting quantity sum was different due to joining the OH Table.Now How do i get the proper Sum.
Expected Result :
Date SUM(od.Quantity)
2016-01-10 4
2016-01-10 1
Sorry For Change In The Question.
You don't need to join
OH table, this can be done with below query:
SELECT O.ID,SUM(od.Quantity) FROM O
INNER JOIN OD ON OD.ID = O.ID
GROUP BY O.ID;
You don't need to join with the OH table.
select O.ID, SUM(OD.Quantity) total_qty
from O inner join OD
on O.ID = OD.ID
group by O.ID;
If you need join with OH, then do it after aggregation.
select *
from OH inner join (
select O.ID, SUM(OD.Quantity) total_qty
from O inner join OD
on O.ID = OD.ID
group by O.ID
) t on t.ID = OH.ID;
Aggregate over the OD
table first in a subquery, then join this to the other two tables:
SELECT t1.Date,
t2.Quantity,
t3.OHI -- and possibly other columns from OH
FROM O t1
INNER JOIN
(
SELECT ID, SUM(Quantity) AS Quantity
FROM OD
GROUP BY ID
) t2
ON t1.ID = t2.ID
INNER JOIN OH t3
ON t1.ID = t3.ID
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.