聚合和连接 2 个表或子查询
Aggregation and joining 2 tables or Sub Queries
我有以下表格。
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
我希望我的输出如下,
Order ID
Qty_shipped
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
我的输出为
Qty_shipped
Total_cost
66
200.16
据我了解,因为我加入了两个表,Qty_shipped被乘了3次,Total_cost被乘了4次。
如有任何帮助,我们将不胜感激。
提前致谢。
加入前需要聚合。或者,将 table 联合在一起然后聚合:
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;
我有以下表格。
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 |
我希望我的输出如下,
Order ID | Qty_shipped | 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
我的输出为
Qty_shipped | Total_cost |
---|---|
66 | 200.16 |
据我了解,因为我加入了两个表,Qty_shipped被乘了3次,Total_cost被乘了4次。
如有任何帮助,我们将不胜感激。
提前致谢。
加入前需要聚合。或者,将 table 联合在一起然后聚合:
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;