SQL - 如果或其他
SQL - if or something else
当我执行 SQL 查询时,我得到下一个:
select Item.No_, Entry.Quantity, MinMax.MaxQuantity, Entry.Location, Item.MainLocation
FROM Item
join Entry
on Item.No_ = Entry.[Item No_]
join MinMax
on Item.No_ = MinMax.Item No_
如果 MainLocation 的 Quantity 是 30,我想在另一个位置将 Quantity 填满到 MaxQuantity。这意味着
主要位置:A1 有 30 个数量,
但位置
A2 有 2 个
A3 有 12 个
A4 有 1 个
我想从 A1 中获取 MaxQuantity 的全部数量,然后我给 A2、A3、A4 并减少 A1。
我想接下来得到:
;with InitialQuery as
(
select Item.No_, Entry.Quantity, MinMax.MaxQuantity, Entry.Location, Item.MainLocation
from Item
join Entry on Item.No_ = Entry.[Item No_]
join MinMax on Item.No_ = MinMax.Item No_
)
, Sources as
(
select * from InitialQuery
where Location=MainLocation and Quantity=30
)
, Destinations as
(
select
i.*,
i.MaxQuantity - i.Quantity 'Needed'
from Sources s
join InitialQuery i on i.No_=s.No_ and i.MainLocation=s.MainLocation and i.Location<>s.Location
)
select
s.No_,
(s.Quantity - d.NoTransferred) 'Quantity',
s.MaxQuantity,
s.Location,
s.MainLocation
from Sources s
join (
select No_, MainLocation, sum(Needed) 'NoTransferred' from Destinations group by No_, MainLocation
) d on d.No_=s.No_ and d.MainLocation=s.MainLocation
union all
select
No_,
MaxQuantity 'Quantity',
MaxQuantity,
Location,
MainLocation
from Destinations
当我执行 SQL 查询时,我得到下一个:
select Item.No_, Entry.Quantity, MinMax.MaxQuantity, Entry.Location, Item.MainLocation
FROM Item
join Entry
on Item.No_ = Entry.[Item No_]
join MinMax
on Item.No_ = MinMax.Item No_
如果 MainLocation 的 Quantity 是 30,我想在另一个位置将 Quantity 填满到 MaxQuantity。这意味着
主要位置:A1 有 30 个数量,
但位置
A2 有 2 个
A3 有 12 个
A4 有 1 个
我想从 A1 中获取 MaxQuantity 的全部数量,然后我给 A2、A3、A4 并减少 A1。
我想接下来得到:
;with InitialQuery as
(
select Item.No_, Entry.Quantity, MinMax.MaxQuantity, Entry.Location, Item.MainLocation
from Item
join Entry on Item.No_ = Entry.[Item No_]
join MinMax on Item.No_ = MinMax.Item No_
)
, Sources as
(
select * from InitialQuery
where Location=MainLocation and Quantity=30
)
, Destinations as
(
select
i.*,
i.MaxQuantity - i.Quantity 'Needed'
from Sources s
join InitialQuery i on i.No_=s.No_ and i.MainLocation=s.MainLocation and i.Location<>s.Location
)
select
s.No_,
(s.Quantity - d.NoTransferred) 'Quantity',
s.MaxQuantity,
s.Location,
s.MainLocation
from Sources s
join (
select No_, MainLocation, sum(Needed) 'NoTransferred' from Destinations group by No_, MainLocation
) d on d.No_=s.No_ and d.MainLocation=s.MainLocation
union all
select
No_,
MaxQuantity 'Quantity',
MaxQuantity,
Location,
MainLocation
from Destinations