[英]Aggregation and joining 2 tables or Sub Queries
我有以下表格。
订单表
Order_ID | Item_ID | 发货数量 |
---|---|---|
1111 | 11 | 4 |
1111 | 22 | 6 |
1111 | 33 | 6 |
1111 | 44 | 6 |
Shipping_det
Order_ID | 船号 | Ship_cost |
---|---|---|
1111 | 1 | 16.84 |
1111 | 2 | 16.60 |
1111 | 3 | 16.60 |
我希望我的 output 如下,
订单编号 | 发货数量 | Ship_cost |
---|---|---|
1111 | 22 | 50.04 |
我写了以下查询,
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
我得到了我的 output
发货数量 | 总消耗 |
---|---|
66 | 200.16 |
据我了解,因为我加入了两张表,所以 Qty_shipped 增加了 3 倍,Total_cost 增加了 4 倍。
任何帮助,将不胜感激。
提前致谢。
您需要在加入之前进行聚合。 或者,将表联合在一起,然后聚合:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.