我的查询如下:
我有一个名为CALLS的表,如下所示:
CALL_NUMBER PART_NUMBER QTY ARRIVAL_DATE
A1 XXX1 5
B2 YYY2 25
C3 ZZZ3 120
D4 ZZZ3 80
E5 ZZZ3 25
另一张表SHIPPING如下:
PART_NUMBER QTY SHIP_DATE ARRIVAL_DATE
XXX1 100 26-Dec 28-Dec
YYY2 5 29-Dec 6-Jan
ZZZ3 200 29-Dec 18-Jan
现在我的目标是根据所发送数量是否满足所需数量,在通话表中输入到货日期。如果没有,则不应在CALLS表中给出日期。
我认为下面的更新查询可能有效:
UPDATE CALLS
SET ARRIVAL_DATE = s.ARRIVAL_DATE
FROM
(
SELECT PART_NUMBER,QTY,ARRIVAL_DATE
FROM SHIPPING
)s
WHERE PART_NUMBER = s.PART_NUMBER
AND QTY < s.QTY
但是,如何从SHIPPING中的提醒中减去分配的数量?
请帮我解决这个问题。
答案 0 :(得分:1)
如果错误,请纠正我。您想要从Calls表更新ARRIVAL_DATE列,如果ARRIVAL_DATE列更新,那么您希望同时从SHIPPING表中减少其QTY值。
如果是,那么这只能通过循环调用表中的每一行并在之后更新发货表来完成。我使用了while循环而不是游标,如下所述:
declare @i int = (select count(*) from calls)
declare @j int = 0
declare @t table
(part_number varchar(10),qty int)
while @j <= @i
begin
update a
set a.arrival_date = b.arrival_date
output inserted.part_number,inserted.qty into @t
from
(select *,row_number() over (order by (select 1)) as rn
from calls
) as a
inner join shipping as b
on a.part_number = b.part_number
where a.qty < = b.qty and a.rn = (case when @j = 0 then 1 else @j end)
update a
set a.qty = a.qty - b.qty
from shipping as a
inner join @t as b
on a.part_number = b.part_number
delete from @t
set @j = @j + 1
end
答案 1 :(得分:0)
您是否只需要从运输中的QTY中减去CALLS中的QTY? (更新时间为12/16,因为原始更新不适合我提议的内容......看一看)
UPDATE CALLS
SET C.PART_NUMBER = S.PART_NUMBER,
C.QTY = SUM(C.QTY - S.QTY),
C.ARRIVAL_DATE = S.ARRIVAL_DATE
FROM SHIPPING S JOIN CALLS C ON C.PART_NUMBER = S.PART_NUMBER
WHERE C.QTY < S.QTY
由于您只是在CALLS中更新了足够数量的那些,所以满足更新ARRIVAL_DATE字段的所有内容 - 除非我误解了某些内容。
请像往常一样使用SQL ..在使用实时数据之前先测试一下这个。 :)