Aggregation/Joins 在订单和运输表中

Aggregation/Joins in Order and Shipping tables

我是 SQL 的新手,我遇到了一个问题。 我有 2 个表,如下所示,

Order_table

Ord_num Ord_date Customer_name Order_total
1111 2021-03-11 ABC 1000

Shipping_table

Ord_num Pkg_num Pkg_weight shipped_date shipping_cost
1111 1 30 2021-03-12 10
1111 2 20 2021-03-13 8

我写了下面的查询,

select sum(order_total), sum(pkg_weight), sum(shipping_cost) 
from order_table O join shipping_table P 
on O.Ord_num = P.Ord_num

这样,如果我将我的订单总计加起来,它显示 2000,但订单只有 1000。

我基本上希望我的输出是,

Ord_num Ord_date Cust_name Order_total Pkg_num shipped_date pkg_weight shipping_cost
1111 2021-03-11 ABC 1000 1 2021-03-12 30 10
1111 2021-03-11 ABC 0 or null 2 2021-03-13 20 8

我希望 Order_total 在第二行中为 0 或 null 的原因是,当我聚合其他列(如 pkg_weight 和 shipping_cost 时,它应该显示它们的总和,而对于 Order_total,它不应显示为 2000,因为订单是 1000,但在两个不同的包装中发货,重量为 2,成本为 2,并且在 2 个不同的日期发货。

任何人都可以帮助我将我的查询写成什么吗?

提前致谢。

从这里开始:

Declare @order_table Table (Ord_num int, Ord_date date, Customer_name varchar(30), Order_total int);
 Insert Into @order_table (Ord_num, Ord_date, Customer_name, Order_total)
 Values (1111, '2021-03-11', 'ABC', 1000)
      , (2222, '2021-04-11', 'XYZ', 2000);

Declare @shipping_table Table (Ord_Num int, Pkg_num int, Pkg_weight int, Shipped_date date, Shipping_cost int)
 Insert Into @shipping_table (Ord_Num, Pkg_num, Pkg_weight, Shipped_date, Shipping_cost)
 Values (1111, 1, 30, '2021-03-12', 10)
      , (1111, 2, 20, '2021-03-13', 8)
      , (2222, 1, 15, '2021-04-12', 5)
      , (2222, 2, 10, '2021-04-13', 3);

 Select ord.Ord_num
      , ord.Ord_date
      , ord.Customer_name
      , Order_total = iif(shp.Pkg_num = 1, ord.Order_total, 0)
      , shp.Pkg_num
      , shp.Shipped_date
      , shp.Pkg_weight
      , shp.Shipping_cost
   From @order_table                    ord
  Inner Join @shipping_table            shp On shp.Ord_Num = ord.Ord_num;

然后可以将其转换为总数:

 Select ord.Ord_num
      , ord.Ord_date
      , ord.Customer_name
      , Order_total = sum(iif(shp.Pkg_num = 1, ord.Order_total, 0))
      , Pkg_weight = sum(shp.Pkg_num)
      , Shipping_cost = sum(shp.Shipping_cost)
   From @order_table                    ord
  Inner Join @shipping_table            shp On shp.Ord_Num = ord.Ord_num
  Group By
        ord.Ord_num
      , ord.Ord_date
      , ord.Customer_name;