[英]Oracle SQL: Insert based on found value in a column given condition from another table
I want to merge my order data into one table which is now in two separate tables: Order ID and customer code in table Orders: 我想将我的订单数据合并到一个表中,该表现在位于两个单独的表中:订单ID和表中的客户代码订单:
Order_ID Customer
1 C11
2 C76
4 C32
and order detalis in table Details (with columns Order_ID, Hour, Quantity) in which the ordered quantity for the hours that the order is valid is given: 并在表格详细信息(包括Order_ID,Hour,Quantity列)中订购detalis,其中给出了订单有效的小时的订购数量:
Order_ID Hour Quantity
1 2 10
1 3 20
2 2 5
2 3 5
2 4 5
4 6 20
4 7 25
I want to merge data of these two tables in one table to have only one row per each order by inserting the quantity for the hours that the order is valid in corresponding column, otherwise zero. 我想在一个表中合并这两个表的数据,通过在相应列中插入订单有效的小时数量,每个订单只有一行,否则为零。
Order_ID Cutomer Hour1 Hour2 Hour3 Hour4 Hour5 Hour6 Hour7 ...
1 C11 0 10 20 0 0 0 0
2 C76 0 5 5 5 0 0 0
4 C32 0 0 0 0 0 20 25
I tried (only for quantity of hour 1): 我试过(仅限小时数1):
insert into Merged_Order_Table
(Order_ID,Customer,Hour1)
select
Orders.Order_id,Orders.Customer,
case
when 1 in (select Details.Hour from Details,Orders where
Details.Order_ID = Orders.Order_ID)
then Details.Quantity
else 0
end
from
Orders
inner join
Details
on
Details.Order_ID = Orders.Order_ID;
But got quantity in Hour1 even for orders with no quantity in this hour. 但是在小时1中获得数量,即使是在这个小时内没有数量的订单。
I question why you would want to take nicely normalized data and put it into a table with that structure. 我怀疑你为什么要采用很好的规范化数据并将其放入具有该结构的表中。 I can understand a query returning the data like that, but another table? 我可以理解一个返回数据的查询,但另一个表?
In any case, your problem is a common problem when using correlated subqueries. 在任何情况下,使用相关子查询时,您的问题是一个常见问题。 The table being correlated is included in the subquery. 相关的表包含在子查询中。 Ooops. 糟糕! Here is fix for that: 这是解决方法:
insert into Merged_Order_Table(Order_ID, Customer, Hour1)
select o.Order_id, o.Customer,
(case when 1 in (select d.Hour from Details d where d.Order_ID = o.Order_ID)
then d.Quantity
else 0
end)
from Orders o;
That said, what you really want is conditional aggregation: 那就是说,你真正想要的是条件聚合:
insert into Merged_Order_Table(Order_ID, Customer, Hour1)
select o.Order_id, o.Customer,
sum(case when d.Hour = 1 then d.Quantity else 0 end)
from Orders o left join
Details d
on o.Order_ID = d.Order_ID
group by o.Order_id, o.Customer;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.