如何从外部引用(SQL)获取更高或更低的值

如何从外部引用(SQL)获取更高或更低的值,sql,sql-server,Sql,Sql Server,我有两个表,一个是关于材料的数据,一个是他们目前的成本批量。然后我有另一个表,包含相同材料的采购规模。然后,我需要从原始表中获取与我的成本批次大小相同或更小的采购规模,以及它上面的采购规模。这在我的select语句中用作相关子查询: Select mbew.Matnr as Material ,mbew.bwkey as Plant ,mbew.STPRS/mbew.peinh as Standard_price ,mbew.verpr/mbew.peinh as Average_price

我有两个表,一个是关于材料的数据,一个是他们目前的成本批量。然后我有另一个表,包含相同材料的采购规模。然后,我需要从原始表中获取与我的成本批次大小相同或更小的采购规模,以及它上面的采购规模。这在我的select语句中用作相关子查询:

Select 
mbew.Matnr as Material
,mbew.bwkey as Plant
,mbew.STPRS/mbew.peinh as Standard_price
,mbew.verpr/mbew.peinh as Average_price
,keko.Costing_lot_size
,Keko.Costing_date
,(select max(info.scale_quantity_konm) as Scale_quantity from dwh.inforecords info where mbew.matnr = info.material and keko.costing_lot_size >= info.scale_quantity_konm) as Current_Costing_Lot_Size
,(select min(info.scale_quantity_konm) as Scale_quantity from dwh.inforecords info where mbew.matnr = info.material and keko.costing_lot_size < info.scale_quantity_konm) as Next_Costing_Lot_Size
,inforecords_larger_price.amount_dkk_konm as Next_Costing_Lot_Size_Price


from 
mbew mbew

left join

(Select kekoa.Material, kekoa.Plant, kekoa.Costing_date, kekoa.Costing_lot_size
from sap.keko Kekoa

inner join 
(select Material, Plant, max(costing_date) as Lates_costing_date from sap.keko
group by material, plant) kekob

on kekoa.costing_date = kekob.Lates_costing_date
and kekoa.Material = kekob.material
and kekoa.plant  = kekob.plant) as keko

on 
mbew.matnr = keko.material
and mbew.bwkey = keko.Plant
但它的效率非常低。它能以某种方式变得更智能/优化吗


提前感谢

您应该添加实体查询我现在已经添加了整个查询。希望这有助于:-