I have the following tables.
Order_table
Order_ID | Item_ID | Qty_shipped |
---|---|---|
1111 | 11 | 4 |
1111 | 22 | 6 |
1111 | 33 | 6 |
1111 | 44 | 6 |
Shipping_det
Order_ID | Ship_num | Ship_cost |
---|---|---|
1111 | 1 | 16.84 |
1111 | 2 | 16.60 |
1111 | 3 | 16.60 |
I want my output to be as follows,
Order ID | Qty_shipped | Ship_cost |
---|---|---|
1111 | 22 | 50.04 |
I wrote the following query,
select sum(O.qty_shipped) as Qty_shipped, sum(S.Ship_cost) as Total_cost
from Order_table O
join shipping_det S on O.Order_ID = S.Order_ID
and I got my output as
Qty_shipped | Total_cost |
---|---|
66 | 200.16 |
As per my understanding, because I joined the two tables, Qty_shipped got multipled 3 times and Total_cost got multiplied 4 times.
Any help would be appreciated.
Thanks in advance.
You need to aggregate before joining. Or, to union the table together and then aggregate:
select order_id, sum(qty_shipped), sum(ship_cost)
from ((select order_id, qty_shipped, 0 as ship_cost
from order_table
) union all
(select order_id, 0, ship_cost
from shipping_det
)
) os
group by order_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.