[英]Joining tables and aggregation/sub queries
I have 2 tables as show below.我有 2 个表格,如下所示。
Table1表格1
Order ID订单编号 | Item_code项目代码 | Sales_Price销售价格 | Qty_ordered订购数量 | Total全部的 | Qty shipped发货数量 |
---|---|---|---|---|---|
1000 1000 | 111 111 | 10 10 | 5 5 | $50 50 美元 | 1 1 |
1000 1000 | 222 222 | 20 20 | 10 10 | $200 200 美元 | 2 2 |
1000 1000 | 333 333 | 30 30 | 15 15 | $450 450 美元 | 0 0 |
I have another table that stores only the details of how much was invoiced (ie how much we shipped)我有另一个表只存储发票金额的详细信息(即我们运送了多少)
Table2 (because we shipped only 10x1 and 20x2 = $50)表 2(因为我们只运送 10x1 和 20x2 = 50 美元)
Order ID订单编号 | Invoice_total发票总额 |
---|---|
1000 1000 | $50 50 美元 |
I wrote the following query,我写了以下查询,
select T1.Order_ID,
sum(T1.Qty_Ordered) as Qty_Ordered,
sum(T1.Total) as Total_Amt_ordered,
sum(T1.Qty_shipped) as Qty_Shipped,
sum(T2.Invoice_total)
from T1 join
T2 on T1.Order_ID = T2.Order_ID
This query gives me the following output, (It is adding $50 to all the rows of T1 Orders).该查询为我提供了以下 output,(它为 T1 订单的所有行增加了 50 美元)。
Order ID订单编号 | Qty_ordered订购数量 | Total全部的 | Qty shipped发货数量 | Invoice_total发票总额 |
---|---|---|---|---|
1000 1000 | 30 30 | $700 700 美元 | 3 3 | $150 150 美元 |
Whereas now, I want my output to be as:而现在,我希望我的 output 为:
Order ID订单编号 | Qty_ordered订购数量 | Total全部的 | Qty shipped发货数量 | Invoice_total发票总额 |
---|---|---|---|---|
1000 1000 | 30 30 | $700 700 美元 | 3 3 | $50 50 美元 |
(because we shipped only $50) (因为我们只发货了 50 美元)
What changes should I make to my query?我应该对我的查询进行哪些更改? I know I can just hard code it but my database has 1000's of orders and 1000's of Half shipped Orders.我知道我可以对其进行硬编码,但我的数据库有 1000 个订单和 1000 个半发货订单。 I want to keep track of Shipped $ (Invoiced $) for all the orders.我想跟踪所有订单的已发货 $(发票 $)。
If I understand correctly, you want:如果我理解正确,你想要:
select T2.Order_ID, T2.Invoice_total,
sum(T1.Qty_Ordered) as Qty_Ordered,
sum(T1.Total) as Total_Amt_ordered,
sum(T1.Qty_shipped) as Qty_Shipped,
from T2 join
T1
on T1.Order_ID = T2.Order_ID
group by T2.Order_ID, T2.Invoice_total;
That is, you don't want to aggregate Invoice_total
.也就是说,您不想聚合Invoice_total
。 You just want it to be a group by
key.你只希望它是一个按键group by
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.