SQL - if或其他

时间:2016-06-08 07:53:56

标签: sql sql-server ssms

当我执行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_

enter image description here

我想如果MainLocation的数量是30,则在另一个位置填写数量到MaxQuantity。这意味着

MainLocation:A1有30个数量,

但位置

A2有2

A3有12个

A4有1个

我想要数量到MaxQuantity,从A1获取,我给A2,A3,A4并减少A1。

我想接下来得到:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

;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
相关问题