27,579
社区成员
发帖
与我相关
我的任务
分享
select A.ItemId,
case when A.InventUnit = A.CostUnit then 1 else B1.Factor end as InventFactor,
case when A.PurchUnit = A.CostUnit then 1 else B2.Factor end as PurchFactor,
case when A.SalesUnit = A.CostUnit then 1 else B3.Factor end as SalesFactor
from A
left join B B1
on A.ItemId = B1.ItemID
and A.InventUnit = B1.FromUnit
and A.CostUnit = B1.ToUnit
left join B B2
on A.ItemId = B2.ItemID
and A.InventUnit = B2.FromUnit
and A.CostUnit = B2.ToUnit
left join B B3
on A.ItemId = B3.ItemID
and A.InventUnit = B3.FromUnit
and A.CostUnit = B3.ToUnit
...
,sB (--筛选出用到的单位换算
SELECT sA.ItemID,
ISNULL(B1.FromUnit,B0.FromUnit) FromUnit,
ISNULL(B1.ToUnit,B0.ToUnit) ToUnit,
ISNULL(B1.Factor,B0.Factor) Factor
FROM sA
LEFT JOIN B1
ON B1.ItemID = sA.ItemID
AND B1.ToUnit = sA.CostUnit
AND ( B1.FromUnit = sA.InventUnit
OR B1.FromUnit = sA.PurchUnit
OR B1.FromUnit = sA.SalesUnit
)
LEFT JOIN B0
ON B0.ItemID IS NULL
AND B0.ToUnit = sA.CostUnit
AND ( B0.FromUnit = sA.InventUnit
OR B0.FromUnit = sA.PurchUnit
OR B0.FromUnit = sA.SalesUnit
)
)
...
WITH sA AS (--筛选出A中的单位
SELECT DISTINCT ItemID, InventUnit, PurchUnit, SalesUnit, CostUnit
FROM A
WHERE InventFactor IS NULL
OR PurchFactor IS NULL
OR SalesFactor IS NULL
)
,sB (--筛选出用到的单位换算
SELECT B.*
FROM B
JOIN sA
ON B.ItemID = sA.ItemID
AND B.ToUnit = sA.CostUnit
AND ( B.FromUnit = sA.InventUnit
OR B.FromUnit = sA.PurchUnit
OR B.FromUnit = sA.SalesUnit
)
)
UPDATE A
SET A.InventFactor = ISNULL(b1.Factor,1),
A.PurchFactor = ISNULL(b2.Factor,1),
A.SalesFactor = ISNULL(b3.Factor,1)
FROM A
LEFT JOIN sB b1
ON A.ItemID = b1.ItemID
-- A.ConstUnit 已经在 sB 中过滤过了,不用写关联了。
AND A.InventUnit = b1.FromUnit
LEFT JOIN sB b2
ON A.ItemID = b2.ItemID
AND A.PurchUnit = b2.FromUnit
LEFT JOIN sB b3
ON A.ItemID = b3.ItemID
AND A.SalesUnit = b3.FromUnit
WHERE A.InventFactor IS NULL
OR A.PurchFactor IS NULL
OR A.SalesFactor IS NULL
select A.ItemId,
ISNULL(B1.Factor,1)as InventFactor,
ISNULL(B2.Factor,1)as PurchFactor,
ISNULL(B3.Factor,1)as SalesFactor
from A
left join B B1
on A.ItemId = B1.ItemID AND A.CostUnit<>A.InventUnit
and A.CostUnit = B1.ToUnit
and A.InventUnit = B1.FromUnit
left join B B2
on A.ItemId = B2.ItemID AND A.CostUnit<>A.PurchUnit
and A.CostUnit = B2.ToUnit
and A.PurchUnit = B2.FromUnit
left join B B3
on A.ItemId = B3.ItemID AND A.CostUnit<>A.SalesUnit
and A.CostUnit = B3.ToUnit
and A.SalesUnit = B3.FromUnit
因为你的查询就表关联查询比较多,我想上索引可能会快些