我有两个表的数据如下
table1:
Order orderitem value
O1 B-IV122 10
O2 B-IV144 10
table2:
order Productionorder productionitem ProductionValue
O1 P1 B-IV122 5
O2 P2 B-IV111 6
O2 P2 CCC144 6
O2 P2 CCC000 4
所需输出:
Order Productionorder orderitem productionitem value ProductionValue
O1 P1 B-IV122 B-IV122 10 5
O2 P2 B-IV144 B-IV111 10 6
我尝试使用以下代码
select order,orderitem,Productionorder,productionitem,value ,ProductionValue from
(select order,orderitem,value from table1) t1
left outer join
(select Order,Productionorder,productionitem,ProductionValue from table2)t2
on t1.order = t2.order and t1.orderitem = t2.productionitem
MY查询输出:
Order Productionorder orderitem productionitem value ProductionValue
O1 P1 B-IV122 B-IV122 10 5
O2 P2 B-IV144 NULL 10 NULL
我想采用以"B"和相应值开头的生产项目(B-IV111(,而不是null。。(注意:我也需要与订单和项目进行连接(。案例没有按预期工作。你能就此向我提出建议吗。
提前谢谢。
SELECT t1.[order]
,orderitem
,value
,productionitem
,productionvalue
FROM table1 t1
INNER JOIN table2 t2 ON t1.[order] = t2.[order]
AND LEFT(t1.orderitem, 3) = LEFT(t2.productionitem, 3)
听起来你想要一个inner join
:
select t1.order, t1.orderitem, t1.Productionorder, t2.productionitem, t1.value, t2.ProductionValue
from table1 t1 join
table2 t2
on t1.order = t2.order and t1.orderitem = t2.productionitem;
子查询根本没有为查询提供任何值,所以我删除了它们。
编辑:
您可以使用outer apply
作为示例:
select t1.order, t1.orderitem, t1.Productionorder,
t2.productionitem, t1.value, t2.ProductionValue
from table1 t1 outer apply
(select top (1) t2.*
from table2 t2
where t1.order = t2.order
order by (case when t1.orderitem = t2.productionitem then 1 else 2 end)
) t2;
注意:这适用于问题中的特定示例。如果您的实际问题更复杂,因为有多行匹配和不匹配,我请求您提出一个新的问题,并提供适当的示例数据、解释和db/sql fiddle,这将非常有帮助。